正如标题所说,我正在尝试找出输入到函数中的数字中每隔一位数字的两个数字的总和。第一个数字将是倒数第二位。例如,输入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;
}
发布于 2019-06-24 09:03:05
你有两个bug。
首先,您希望每个循环只执行一次shifter = 100 * shifter;
。在每次迭代中,您希望shifter
是上一次迭代的100倍。所以只需乘以100一次。你可以摆脱incrementer
了。这是多余的。
其次,您的示例显示了将16的数字相加得到7,但是由于某种原因,您注释掉了执行此操作的代码。
int everyOther (long num)
{
int shifter = 1; // dividing by 10 gets us the hundreds digit
int total = 0;
int a = 0;
while (num/shifter > 0)
{
shifter *= 100; // move two digits over
if(num/shifter == 0)
{
break;
}
a = 2 * ((num / shifter) % 10);
total += (a/10 + a%10);
}
return total;
}
https://stackoverflow.com/questions/56728736
复制相似问题