Leetcode 258 Add Digits

题目:
258 Add Digits

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 = 11, 1 + 1 = 2. Since 2 has only one digit, return it.

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

public int addDigits(int num) {
        int result = num;
        Integer I_num = new Integer(num);
        String s = I_num.toString();
        int len = s.length();
        while(len>1){
            result = 0;
            for(int i = 0; i < len; i++){
                result += (s.charAt(i)-'0');
            }
            I_num = new Integer(result);
            s = I_num.toString();
            len = s.length();
        }
        System.out.println(I_num);
        return result;
    }

测试运行时间24s 比较慢,

改进算法如下:

 public int addDigits(int num) {
       if(num<10){
            return num;
        }
        int result = add_bit(num);
        while(result>=10){
            result = add_bit(result);
        }

        return result;
    }
    public int add_bit(int num){
        int result = 0;
        while(num>0){
            result += num%10;
            num = num/10;
        }
        return result;
    }

测试运行时间3ms

你可能感兴趣的:(LeetCode,算法)