各位相加

题目描述:给定一个非负整数 num,反复将各个位上的数字相加,直到结果为一位数。

示例说明请见LeetCode官网。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/add-digits/
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解法一:循环

声明一个变量result初始化为num,不同的将各数位的数字相加,然后再将结果赋值给result,循环处理,直到result的值为个位数,最后返回result。

  1. public class LeetCode_258 {
  2. public static int addDigits(int num) {
  3. // 最后的返回值
  4. int result = num;
  5. while (result >= 10) {
  6. int temp = 0;
  7. // 各个数位相加
  8. while (result > 10) {
  9. temp += result % 10;
  10. result = result / 10;
  11. }
  12. if (result == 10) {
  13. temp += 1;
  14. } else {
  15. temp += result;
  16. }
  17. result = temp;
  18. }
  19. return result;
  20. }
  21. public static void main(String[] args) {
  22. System.out.println(addDigits(385));
  23. }
  24. }

【每日寄语】 耐心是百折不挠的东西,无论于得于失,都是最有用的。