#include <bits/stdc++.h>
using namespace std;
// 求一个整数的所有数位之和
void solve()
{
int n;
cin >> n;
int ans = 0;
while (n)
{
ans += n % 10; // 取个位值
n /= 10; // 整体右移一位
}
cout << ans << endl;
}
signed main()
{
ios::sync_with_stdio(false);
int t;
// cin >> t;
t = 1;
while (t--)
solve();
return 0;
}
你也可以使用 to_string
将整数转换为字符串,然后遍历字符串求和。