【问题标题】:Sum up all digits of a number till it becomes a single digit [closed]总结一个数字的所有数字,直到它变成一个数字[关闭]
【发布时间】:2014-05-18 02:23:40
【问题描述】:

这不是学校作业或我的作业。事实上,我提出了这个问题。我一直在研究和测试仅使用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.

如果允许我们使用条件语句,这个问题就非常简单。但是,如果我们不能使用,我们还能解决它吗:

-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

注意:我不是在讨论能不能解决。我知道这是可以做到的。

【问题讨论】:

  • CodeGolf 是一个更好的网站...您的问题是什么?
  • 顺便说一句,您的问题和接受的答案都不是新的或困难的。请参阅:Digital rootCongruence formula
  • 版主注意请尽量减少讨论并切合主题。使用聊天进行扩展讨论,而不是 cmets。
  • 这个问题似乎是题外话,因为它是一个代码高尔夫挑战

标签: c++ loops math operators


【解决方案1】:

其实很简单:

int singleDigitSum(int n) {
  int sum = n % 9;
  while (sum == 0) {
    sum += 9;
  }
  return sum;
}

解释:对于给定的数字 N,这个单个数字的和实际上是 N 的余数除以 9,或者,如果余数为 0,则为 9 本身。因此,在最后一种情况下,此处的循环仅用于将结果“快进”到 9。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多