A - Digit Sum 2
Time limit : 2sec / Memory limit : 256MB
Score : 300 points
Problem Statement
Find the maximum possible sum of the digits (in base 10) of a positive integer not greater than N.
Constraints
- 1≤N≤1016
- N is an integer.
Input
Input is given from Standard Input in the following format:
N
Output
Print the maximum possible sum of the digits (in base 10) of a positive integer not greater than N.
Sample Input 1
100
Sample Output 1
18
For example, the sum of the digits in 99 is 18, which turns out to be the maximum value.
Sample Input 2
9995
Sample Output 2
35
For example, the sum of the digits in 9989 is 35, which turns out to be the maximum value.
Sample Input 3
3141592653589793
Sample Output 3
137
【题目大意】
求不超过给定值的所有数的集合中,各位数字之和最大值为多少。
【解题思路】
进行一下字符串处理,从个位向上找不为9的数,如果搜索到开头还没有搜索到(即都为9,这时候该数就是最大的),若在其中搜索到不为九的,那么集合中各位数字之和的最大值就是:首位-1+其余位数*9。
【解题代码】
#include <cstdio>
#include <cstring>
#include <cmath>
#include <queue>
#include <set>
#include <map>
#include <algorithm>
using namespace std;
char num[20];
int main()
{
while(~scanf("%s",num))
{
int len=strlen(num);
int i=len-1;
for(;i>=0;i--)
{
if(num[i]!='9') break;
}
if(i==-1) printf("%d\n",len*9);
else if(i==0) printf("%d\n",(len-1)*9+num[0]-'0');
else printf("%d\n",(len-1)*9+num[0]-'0'-1);
}
return 0;
}
【收获与反思】
简单处理,注意边界情况即可。