use*_*460 -5 c++ math loops operators
这不是学校的工作或我的任务.事实上,我提出了这个问题.我一直在研究和测试只single while loop使用基本操作符+-*/%和基本变量int value来执行任务的可能性.我想知道在不使用任何其他控制结构的情况下可以实现多少.
这是我的编程问题:
使用单个while循环来汇总正数的所有数字,直到它变为单个数字.例如:
778899 becomes 7+7+8+8+9+9=48.
48 becomes 4+8=12.
12 becomes 1+2=3.
Final number is 3.
Run Code Online (Sandbox Code Playgroud)
如果我们被允许使用条件语句,这个问题非常容易.但是,如果我们不能使用,我们仍然可以解决它:
-any conditional statements (if/switch case)
-any ternary operators
-any function calls
-any recursive calls
-any other data structures like arrays/lists/vectors/pointers..
-any bit shift operators
Run Code Online (Sandbox Code Playgroud)
注意:我不是在讨论它是否可以解决.我知道可以做到.
这很简单,实际上:
int singleDigitSum(int n) {
int sum = n % 9;
while (sum == 0) {
sum += 9;
}
return sum;
}
Run Code Online (Sandbox Code Playgroud)
说明:对于给定的数字N,该单个数字和实际上是N的余数除以9,或者,如果该余数为0,9本身.所以这里的循环仅用于在最后一种情况下将结果"快进"到9.
| 归档时间: |
|
| 查看次数: |
1836 次 |
| 最近记录: |