[leetcode]: 258. Add Digits

古城微笑少年丶 2022-06-16 01:25 561阅读 0赞

1.题目描述
Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.
翻译:给定一个非负整数,反复的将它各位上的数相加,直到变为一位数。
例如:38-》3+8=11-》1+1=2

2.分析
不谈数学技巧,简单while循环即可。

3.代码

  1. class Solution {
  2. public:
  3. int addDigits(int num) {
  4. while (num > 9) {
  5. int temp = num;
  6. num = 0;
  7. while (temp > 0) {
  8. num += temp % 10;
  9. temp = temp / 10;
  10. }
  11. }
  12. return num;
  13. }
  14. };

发表评论

表情:
评论列表 (有 0 条评论,561人围观)

还没有评论,来说两句吧...

相关阅读