[抄題]: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; } }