258. Add Digits 入学考试:数位相加

[抄题]:

Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.

Example:

Input: 38
Output: 2 
Explanation: The process is like: 3 + 8 = 11, 1 + 1 = 2. 
             Since 2 has only one digit, return it.

 [暴力解法]:

时间分析:

空间分析:

 [优化后]:

时间分析:

空间分析:

[奇葩输出条件]:

[奇葩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;
    }
}
View Code
原文地址:https://www.cnblogs.com/immiao0319/p/9589898.html