正如标题所说,我正在尝试找出输入到函数中的数字中每隔一位数字的两个数字的总和。第一个数字将是倒数第二位。例如,输入58423应该返回2*2 (4),8*2 (16-> 1+6 = 7) -- >4+7 = 11。函数如下所示。
我使用的事实是,n%10将得到n的最右边的数字,而(n / 10) % 10将得到n的下一个最右边的数字,依此类推,其中n是输入的数字。
int everyOther(long num) //(n / 10) % 10 will get you the next rightmost
digit
{
int incrementer = 1;
int total = 0;
long shifter = 1;
int a = 0;
while(true)
{
shifter = shifter *100;
if(num/shifter == 0)
{
break; // will have reached the end of the number if this is
//true
}
a = 2* ((num / shifter) % 10); // every other digit right to left
//starting from the second to last, multiplied by two
total = total + (a/10 + a%10); //sum of the above product's
//digits
incrementer++;
}
return total;
}
https://stackoverflow.com/questions/56728736
复制相似问题