Leetcode 258. Add Digits
Posted rainsoul~~
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode 258. Add Digits相关的知识,希望对你有一定的参考价值。
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?
使用循环的解法如下:
1 int addDigits(int num) { 2 int sum = 0; 3 while (num / 10) 4 { 5 while (num / 10) 6 { 7 sum += num % 10; 8 num = num / 10; 9 } 10 sum += num; 11 num = sum; 12 sum = 0; 13 } 14 sum += num; 15 return sum; 16 }
不使用循环的解法,参考了知乎,代码如下:
1 int addDigits(int num) 2 { 3 if(num % 9 == 0 && num != 0) 4 return 9; 5 else 6 return num % 9; 7 }
贴一张图片在这里:
以上是关于Leetcode 258. Add Digits的主要内容,如果未能解决你的问题,请参考以下文章