列表

详情


NC25353. Maximum Sum of Digits

描述

输入描述

输出描述

示例1

输入:

2
35
1000000000

输出:

17
82

说明:

In the first example, you can choose, for example,a = 17 andb = 18, so thatS(17) + S(18) = 1 + 7 + 1 + 8 = 17. It can be shown that it is impossible to get a larger answer.

In the second test example, you can choose, for example,a = 500000001 andb = 499999999, withS(500000001) + S(499999999) = 82. It can be shown that it is impossible to get a larger answer.

原站题解

上次编辑到这里,代码来自缓存 点击恢复默认模板

C++14(g++5.4) 解法, 执行用时: 4ms, 内存消耗: 404K, 提交时间: 2019-04-27 23:33:04

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
ll work(ll n){
	ll sum=0;
	while(n){
		sum+=n%10;
		n/=10;
	}
	return sum;
}
int main(){
	int t;
	ll n,x;
	cin>>t;
	while(t--){
		cin>>n;
		int k=log10(n);
		x=pow(10,k)-1;
		cout<<work(x)+work(n-x)<<endl;
	}
	return 0;
}

pypy3 解法, 执行用时: 54ms, 内存消耗: 21140K, 提交时间: 2023-05-07 17:59:17

n=int(input())
for i in range(n):
    x=int(input())
    if x<10:
        print(x)
    else:
        a=int((len(str(x))-1)*'9')
        b=x-a
        a=sum(list(map(int,str(a))))
        b=sum(list(map(int,str(b))))
        print(a+b)

C++11(clang++ 3.9) 解法, 执行用时: 3ms, 内存消耗: 348K, 提交时间: 2019-04-25 14:46:45

#include<bits/stdc++.h>
using namespace std;
int main(){
	long long n,a=0;
	int t;cin>>t;
    while(cin>>n){
        a=0;
	    while(n>9){n-=9;a+=9+n%10;n/=10;}
	    cout<<n+a<<endl;
    }
	return 0;	
}

Python3(3.5.2) 解法, 执行用时: 29ms, 内存消耗: 3404K, 提交时间: 2019-04-26 12:08:12

input();
while True:
    try:
        n=int(input());
        s=0
        while n>8:
            s+=(9+(n-9)%10)
            n=int((n-9)/10)
        print(int(s+n))
    except:
        break;

上一题