您的位置:首页 > 其它

Leetcode-258-Add Digits

2016-09-28 13:11 309 查看
题目要求:

Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.

给定一个非负的整型数,重复加其每位,知道结果是一位数。

例:Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it.

解题思路:

多试几个数,找规律,发现相加后所得的数比原来的数减少9的倍数:即

12-(1+2)=9;26-(2+6)=18;39-(3+9)=27…..

代码如下:

<script type="text/javascript">
var addDigits = function(num){
var sum ;
sum = 1 + (num - 1)%9;
return sum;
}
</script>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: