本文介绍了总和的所有数字对于一个给定的正数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
方法的返回值应该一样,如果输入了数字,假设345,则输出应该是3 + 4 + 5 = 12 - > 1 + 2 = 3 我在做什么错在这里?
公共类DigitSum
{
INT总和= 0;
公众诠释计算(INT MethParam)
{
INT REM = MethParam%10;
总和+ = REM;
MethParam = MethParam / 10;
如果(MethParam→10)
计算(MethParam);
返回总和+ MethParam;
}
公共静态无效的主要(字串[] args)
{
DigitSum ds为新DigitSum();
的System.out.println(ds.compute(435));
}
}
解决方案
O(1)算法中的求和位数:
考虑的任何数量的模9将返回该号码的数字的总和而获得的单个数字编号,直至
如果数是9的倍数,则总和将将是9
单行:
公众诠释sumDigit(INT N){
收益率(N%9 == 0安培;&安培; N = 0!)? 9:N%9;
}
另一种实现:
公众诠释sumDigit(INT N){
INT总和= N%9;
如果(总和== 0){
如果(正大于0)
返回9;
}
返回总和;
}
Method return should be like if entered a number, suppose 345, then output should be 3+4+5=12 --> 1+2 = 3. what i am doing wrong here?
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) Algo for sum Of digits :
Taking the modulo 9 of any number will return the sum of digits of that number until a single digit number is obtained.
If the number is a multiple of 9, then the sum will will be 9
one liner :
public int sumDigit(int n){
return (n%9 == 0 && n != 0) ? 9 : n%9;
}
Alternate implementation :
public int sumDigit(int n){
int sum = n % 9;
if(sum == 0){
if(n > 0)
return 9;
}
return sum;
}
这篇关于总和的所有数字对于一个给定的正数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!