[Leetcode从零开刷]258. Add Digits

来源:互联网 发布:vb九九乘法表左上三角 编辑:程序博客网 时间:2024/06/06 00:36

题目来源leetcode
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?


翻译:
给你一个非负整数,重复相加它的每个数字,直到结果只剩一个数字。举例:数字38–>3+8=11–>1+1=2–>结果就是返回2。
追加的要求就是运算速度要块O(1),不用递归。


解题:(我的方法比较笨,先看看到底是怎么输出的找规律)
先举例子枚举法:
0 –>0
1 –>1
2 –>2
3 –>3
4 –>4
5 –>5
6 –>6
7 –>7
8 –>8
9 –>9
10 –>1

18 –>9
19 –>1
20 –>2

27 –>9
28 –>1
我们发现数字的返回非常有规律基本就是从1到9的轮回。每到9的整数倍时即是9,不然返回的值均是此数除以9的余数。
所以有如下代码:

cpp:

class Solution {public:    int addDigits(int num) {        if(num == 0)            return 0;        else             return (num-1)%9 +1;            }};
原创粉丝点击