第十周作业: Add Digits

来源:互联网 发布:传奇数据库编辑工具 编辑:程序博客网 时间:2024/05/29 14:00
题面:

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?

题解:将每个数的各个位上的数字加起来,若大于9,则继续加,个位数则输出。则自然可想到,模除和累加,一个while即可。做完后觉得很笨。思考后则可得任何大于9得数按此法即是求对9的模。则可更简便。

class Solution {public:    int addDigits(int num) {            while(num>9){                 int sum=0;                 while(num){                  sum+=num%10;                  num/=10;                 }                  num=sum;                 }                 return num;    }};
class Solution {public:    int addDigits(int num) {        return(1+(num-1)%9);    }};


原创粉丝点击