洛谷 B4065:[GESP202412 二级] 数位和 ← 字符串

【题目来源】
https://www.luogu.com.cn/problem/B4065

【题目描述】
小杨有 n 个正整数,小杨想知道这些正整数的数位和中最大值是多少。“数位和”指的是一个数字中所有数位的和。例如:对于数字 12345,它的各个数位分别是 1,2,3,4,5。将这些数位相加,得到 1+2+3+4+5=15。因此,12345 的数位和是 15。

【输入格式】
第一行包含一个正整数 n,代表正整数个数。
之后 n 行,每行包含一个正整数。

【输出格式】
输出这些正整数的数位和的最大值。​​​​​​​

【输入样例】
3
16
81
10​​​​​​​

【输出样例】
9

【数据范围】
对于全部数据,保证有 1≤n≤10^5,每个正整数不超过 10^12。

【算法分析】
由于数据会达到 10^12,所以选择使用“字符串”进行处理。否则,需要使用 long long 型。

【算法代码】

#include <bits/stdc++.h>
using namespace std;

int n;
string s;
int imax=INT_MIN;

int main() {
    cin>>n;
    while(n--) {
        cin>>s;
        int sum=0;
        for(int i=0; i<s.size(); i++) {
            sum+=s[i]-'0';
        }
        imax=max(imax,sum);
    }
    cout<<imax;

    return 0;
}

/*
in:
3
16
81
10

out:
9
*/





【参考文献】
https://www.luogu.com.cn/problem/solution/B4065
https://www.acwing.com/blog/content/406/



 

 

posted @ 2025-12-21 04:41  Triwa  阅读(4)  评论(0)    收藏  举报