给定正数的所有数字总和

2020年11月29日 67点热度 0条评论

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable,
visit the help center

7年前关闭。

方法返回应该像输入数字一样,假设为345,则输出应为3 + 4 + 5 = 12-> 1 + 2 =3。我在这里做错了什么?

public class DigitSum
 {
    int  Sum=0;

    public int compute( int MethParam )
    {
        int rem = MethParam%10; 
        Sum+=rem;        

        MethParam = MethParam/10; 
        if(MethParam>10)
            compute(MethParam);

        return Sum+MethParam;  
    }

  public static void main(String[] args)
  {
    DigitSum ds  = new DigitSum();
    System.out.println(ds.compute(435));
  }
}

 

解决方案如下:

 

O(1)表示数字总和的算法:

取任何数字的模9将返回该数字的总和,直到获得单个数字为止。

如果数字是9的倍数,则总和将为9

一线

public int sumDigit(int n){
    return (n%9 == 0 && n != 0) ? 9 : n%9;
}

替代实现:

public int sumDigit(int n){

      int sum = n % 9;
      if(sum == 0){
          if(n > 0)
               return 9;
      }
      return sum;
}