LeetCode258 各位相加

题目链接:https://leetcode-cn.com/problems/add-digits/

给定一个非负整数 num,反复将各个位上的数字相加,直到结果为一位数。

示例:

输入: 38
输出: 2 
解释: 各位相加的过程为:3 + 8 = 11, 1 + 1 = 2。 由于 2 是一位数,所以返回 2。

进阶:
你可以不使用循环或者递归,且在 O(1) 时间复杂度内解决这个问题吗?

常规思路:

1 int addDigits(int x) {
2     if(x<10) return x;
3     int sum=0;
4     while(x){
5         sum+=x%10;
6         x/=10;
7     }
8     return addDigits(sum);
9 }

 优化后的:找规律%9

1 int addDigits(int x) {
2     if(x==0) return 0;
3     else if(x%9==0) return 9;
4     else return x%9;
5 }
原文地址:https://www.cnblogs.com/shixinzei/p/10686456.html