题解 | #数位之和#

数位之和

https://ac.nowcoder.com/acm/problem/22199

#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 将整数转换为字符串,然后遍历字符串求和。

全部评论

相关推荐

评论
3
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务