leetcode学习篇五——Add Digits

来源:互联网 发布:uuu网络加速器下载 编辑:程序博客网 时间:2024/06/13 00:37

题目如下:
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?
题目要求能不能在O(1)的时间里求出来,所以感觉应该是有某种规律可以直接推出结果的,所以从1开始列了数字然后算出结果,果真存在规律,从1到9然后又是从1到9,得到一下代码,通过。

class Solution {public:    int addDigits(int num) {        return num==0?0:(num%9==0?9:num%9);    }};
0 0
原创粉丝点击