【一天一道LeetCode】#258. Add Digits

来源:互联网 发布:网络第二办公室答案 编辑:程序博客网 时间:2024/05/29 16:36

一天一道LeetCode

本系列文章已全部上传至我的github,地址:ZeeCoder‘s Github
欢迎大家关注我的新浪微博,我的新浪微博
欢迎转载,转载请注明出处

(一)题目

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) {        int ret = num;        while(ret>=10)        {            int sum = 0;            int temp = ret;            while(temp){//每次计算每一位上的和                sum+=temp%10;                temp/=10;            }             ret = sum;        }        return ret;    }};

循环很简单,计算每一位的和,判断和是否为一位数,依次循环。

后来,突然看到题目中写了:Could you do it without any loop/recursion in O(1) runtime?

什么?O(1)时间!不用循环!下面看解法二的思路。

解题思路二

既然不用循环,就开始找规律,发现一直是1-9在循环,所以很容易想到mod9

要注意以下两个特殊情况:

(1) 0的时候为0
(2) mod9==0,此时返回9(除0外)

class Solution {public:    int addDigits(int num) {        if(num==0) return 0;//特殊情况0        return num%9==0?9:num%9;    }};
0 0