2018.3.4【 AtCoder - 3867 】解题报告(字符串处理,数学)

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

  • 1N1016
  • 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

Copy
100

Sample Output 1

Copy
18

For example, the sum of the digits in 99 is 18, which turns out to be the maximum value.


Sample Input 2

Copy
9995

Sample Output 2

Copy
35

For example, the sum of the digits in 9989 is 35, which turns out to be the maximum value.


Sample Input 3

Copy
3141592653589793

Sample Output 3

Copy
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;
} 

【收获与反思】

简单处理,注意边界情况即可。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值