Maximum Sum of Digits

链接:https://ac.nowcoder.com/acm/contest/877/K
来源:牛客网

题目描述

输入描述:

 
 

输出描述:

 
 

示例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.

题意:题意就是给你一个n,你需要找到a,b,要求a+b=n,并且要求a,b的各位数字之和最大

这里就是尽可能的让一个数有最多的9

#include <bits/stdc++.h>
#define LL long long
using namespace std;
char str[100],a[100],b[100];
void work(){
    scanf("%s",str);
    int len = strlen(str);
    LL n = 0;
    for (int i=0;i<len;i++) 
	    n = n * 10 + str[i] - '0';//先把n求出来 
    a[0] = str[0] - 1;
    for (int i=1;i<len;i++) 
	    a[i] = '9';//9尽可能的多 
    a[len] = 0;//不用控制for循环的范围了 
    LL A = 0;
    for (int i=0;i<len;i++) 
	    A = A * 10 + a[i] - '0';//第一个数 
    int ans = 0 ;
    for (int i=0;i<len;i++) 
	    ans += a[i] - '0';
    LL B = n - A;//第二个数 
    while (B){
        ans += B % 10;
        B /= 10;
    }
    printf("%d\n",ans);
}
int main(){
    int t;
	scanf("%d",&t);
    while (t--) 
	    work();
    return 0;
}

猜你喜欢

转载自blog.csdn.net/red_red_red/article/details/89526769