leetcode 258 Add Digits

来源:互联网 发布:伊登软件股份有限公司 编辑:程序博客网 时间:2024/06/03 17:52

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?


class Solution {public:    int addDigits(int num) {        return (num-1)%9+1;    }};

设数字为四位数,各个位分别是abcd,其他情况类似。

abcd=a*1000+b*100+c*10+d

        =a+b+c+d+(a*999+b*99+c*9)

        =a+b+c+d+(a*111+b*11+c)*9

设n=a+b+c+d

n同样可以做如上展开,反复迭代,直到前面数字之和为个位数,形如n+m*9并且此时这个个位数的取得满足题目的要求的返回值,此时后面的数字为9的倍数。要求的这个个位数只需对九求模即可(因为这个数可能是9,所以要先减一最后加一)。

0 0
原创粉丝点击