【leetcode】258. 各位相加

2023-05-31,,

leetcode258. 各位相加

C++解法:

class Solution {
public:
int addDigits(int num)
{
string s;//用来将num转换成字符串
while(num>=10)
{
int sum=0;//初始化累加和
s=to_string(num);
for(int i=0;i<s.size();i++)
{
sum+=s[i]-'0';//依次将各位上的数字加到累加器中
}
num=sum;//给num重新赋值
}
return num;//跳出循环时说明num已经小于10,返回num即可
}
};

python3解法:

class Solution:
def addDigits(self, num: int) -> int:
def pending_num(num):
sum = 0
while num:
sum += num % 10
num //= 10
return sum
while num >= 10:
num = pending_num(num)
return num

【leetcode】258. 各位相加的相关教程结束。

《【leetcode】258. 各位相加.doc》

下载本文的Word格式文档,以方便收藏与打印。