zoukankan      html  css  js  c++  java
  • LeetCode(258):Add Digits

    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.

    题意:将给定的整数各个位数相加,直到相加之和小于10。

    思路:(1)常规的解法,求和之后进行判断,然后在进行求和直至满足条件;(2)参考Digital root的定义进行求解。

    代码:

    第一种思路:

    //求整数的各位之和
            public int get_sum(int sum)
            {
             int count = 0;
             while(sum>0){
                 count = count + sum%10;
                 sum/=10;
             }
             return count;
            }
         public int addDigits(int num) {
             int sum=0;
              while(true)
              {
                  sum= get_sum(num);
                  if(num<=9) 
                    {
                          return sum;
                    }
                  else 
                  {
                    num = sum;
                  }
              }
          }

    第二种思路:

    public int addDigits(int num) {
                if (num == 0) return 0;
                if (num%9==0) return 9;
                if(num<9) {
                    return num;
                }else{
                    return addDigits(num % 9);
                }
            }
  • 相关阅读:
    精准测试
    git 管理
    git
    代码覆盖率测试
    vue 前端视频
    jenkins
    go学习资料
    4-4 求自定类型元素的平均
    4-3 简单求和
    4-2 多项式求值
  • 原文地址:https://www.cnblogs.com/Lewisr/p/5122343.html
Copyright © 2011-2022 走看看