[抄题]:java
Given a non-negative integer num
, repeatedly add all its digits until the result has only one digit.git
Example:算法
Input:
Output: 2
Explanation: The process is like: , .
Since has only one digit, return it.383 + 8 = 111 + 1 = 22
[暴力解法]:数据结构
时间分析:ide
空间分析:oop
[优化后]:优化
时间分析:spa
空间分析:debug
[奇葩输出条件]:code
[奇葩corner case]:
[思惟问题]:
while循环写得太少,潜意识里仍是for循环
//id: yuec2 name:Yue Cheng package day1test; import java.util.Scanner; public class Numerologist { public static void main(String[] args) { Numerologist n = new Numerologist(); System.out.println("Enter an integer"); Scanner input = new Scanner(System.in); int number = input.nextInt(); System.out.println("Your lucky number is " + n.getLuckyNumber(number)); input.close(); } int getLuckyNumber(int num) { //write your code here int number = Math.abs(num); String str = String.valueOf(number); char digits[] = str.toCharArray(); while (digits.length != 1) { int sum = 0; for (int i = 0; i < digits.length; i++) { sum += digits[i] - 'a'; } str = String.valueOf(sum); digits[] = str.toCharArray(); } if (digits.length == 1) { int result = digits[0] - 'a'; return result; } return 0; } }
[英文数据结构或算法,为何不用别的数据结构或算法]:
[一句话思路]:
最基本的while循环吧
[输入量]:空: 正常状况:特大:特小:程序里处理到的特殊状况:异常状况(不合法不合理的输入):
[画图]:
[一刷]:
corner case没注意,小于10的数字直接返回num自己
[二刷]:
[三刷]:
[四刷]:
[五刷]:
[五分钟肉眼debug的结果]:
[总结]:
练习多写while循环吧
[复杂度]:Time complexity: O(n) Space complexity: O(1)
[算法思想:迭代/递归/分治/贪心]:
[关键模板化代码]:
[其余解法]:
[Follow Up]:
[LC给出的题目变变变]:
[代码风格] :
[是否头一次写此类driver funcion的代码] :
[潜台词] :
class Solution { public int addDigits(int num) { //corner case if (num == 0) return 0; //while loop while (num >= 10) { int sum = 0; //add every digit while (num > 0) { sum += num % 10; num /= 10; } //assign the sum to the new num num = sum; } //return return num; } }