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?

笔和纸真的是解题神器

刚看完题,我确实想复杂了。看了Hint的第二句,用笔纸写了前30位自然数的结果,发现答案很明显。

写代码就讲究个“无微不至”

本以为一句return num % 9就华丽的收场了,却忘记了9 % 9 = 0的情况。导致一次Failed。

直接贴代码喽:

class Solution {
public:
    int addDigits(int num) {
        //看到hint第二条2.What are all the possible results?有了启发。
        //所有的正数的最后结果是1~9的循环。
        if(num)
        {
            if(num % 9) //处理9%9=0的情况
                return num % 9;
            else return 9;
        }
        else{
            return 0;//0的情况。
        }
    }
};

今天周六,夏季赞美之夜刚彩排结束,小主持加油,身体加油,赞美神!开心收场,晚安。
2016.7.16 22:00-22:45
——End——

你可能感兴趣的:(258.[每位数相加] Add Digits)