258. Add Digits
程序员文章站
2022-06-04 10:44:51
...
Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.
Example:
Input: 38
Output: 2
Explanation: The process is like: 3 + 8 = 11, 1 + 1 = 2.
Since 2 has only one digit, return it.
题解:
#include <iostream>
#include <string>
using std::cout;
using std::endl;
using std::to_string;
int AddDigits(int num);
int Sum(int num);
int main(int argc, const char* argv[]) {
int num = 38;
cout << AddDigits(num) << endl;
system("pause");
return 0;
}
int AddDigits(int num) {
do {
num = Sum(num);
} while (to_string(num).size() != 1);
return num;
}
int Sum(int num) {
if (num == 0)
return 0;
return num % 10 + Sum(num / 10);
}
上一篇: 性感女人的真谛,胸大妹子美!不可挑剔!
下一篇: 华为P30 Pro暴力测试:结果给力
推荐阅读
-
Java基础学习总结(129)——Arrays.asList得到的List进行add和remove等操作出现异常解析
-
Java中List add添加不同类型元素的讲解
-
MySQL添加外键时报错:1215 Cannot add the foreign key constraint的解决方法
-
解决Eclipse add external jars运行出现java.lang.NoClassDefFoundError的方法
-
MySQL的Data_ADD函数与日期格式化函数说明
-
MySQL添加外键时报错:1215 Cannot add the foreign key constraint的解决方法
-
解决Eclipse add external jars运行出现java.lang.NoClassDefFoundError的方法
-
ERROR StatusLogger Log4j2 could not find a logging implementation. Please add log4j-core to the classpath. Using SimpleLogger to log to the console...
-
MySQL的Data_ADD函数与日期格式化函数说明
-
Python使用add_subplot与subplot画子图操作示例