[LeetCode 258] Add Digits

来源:互联网 发布:触摸屏软件下载 编辑:程序博客网 时间:2024/06/05 03:37

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

For example:

Given num = 38, the process is like: 3 + 8 = 111 + 1 = 2. Since 2 has only one digit, return it.

Follow up:

Could you do it without any loop/recursion in O(1) runtime?

Solution:
1) while loop until the number is no longer bigger than 9.
public int addDigitsLoop(int num) {    if(num < 10) {        return num;    }    while(num > 9) {        String str = "" + num;        int addition = 0;        for (int i = 0; i < str.length(); i++) {            String temp = "" + str.charAt(i);            addition += Integer.parseInt(temp);        }        num = addition;    }    return num;}
2) recursion
public int addDigits(int num) {    if(num < 10) {        return num;    }    String str = "" + num;    int addition = 0;    for(int i=0; i<str.length();i++) {        String temp = "" + str.charAt(i);        addition += Integer.parseInt(temp);    }    if (addition > 9) {        addition = addDigits(addition); // remember to assign the value to a variable    }    return addition;}

注:这些方法都很 naive,还要把num 转换成字符串,这样过于繁琐,效率太低。 明天考虑考虑不用字符串的方法。
0 0
原创粉丝点击