258.Add Digits

女爷i 2022-06-09 03:54 259阅读 0赞
  1. /*
  2. Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.
  3. For example:
  4. Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it.
  5. Follow up:
  6. Could you do it without any loop/recursion in O(1) runtime?
  7. */
  8. int a[101];
  9. int addDigits(int num) {
  10. int i;
  11. while(num>=10)
  12. {
  13. num = getArray(num);//直到num小于10才返回
  14. }
  15. return num;
  16. }
  17. int getArray(int total)
  18. {
  19. int i,count = 0, res = 0;
  20. for(i = 0; total != 0 ; i++)//将数字分配到数组中
  21. {
  22. a[i] = total % 10;
  23. total = total / 10;
  24. count++;
  25. }
  26. for(i = 0 ; i < count ; i++)//累加起来
  27. res = res + a[i];
  28. return res;
  29. }

发表评论

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

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

相关阅读