258: Add Digits
Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.
For example:
Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it.
【题目大意】给定一个数,不断地把这个数的每个数位相加,直到这个数变成一位数
【解法】数位分离,每次分离出个位数加到原数字上,直到只剩一个数位
【AC代码】
int addDigits(int num) {
while(num >= 10){
num = num / 10 + num % 10;
}
return num;
}
本文介绍了一种将非负整数不断拆分为个位数并相加直至仅剩一位数的算法实现。通过循环分离个位数的方式,该算法能够高效地解决这一问题。
673

被折叠的 条评论
为什么被折叠?



