AtCoder Grand Contest 021A - Digit Sum 2

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

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

Submit

       在AtCoder上的第一场比赛,发篇文章感慨一下。

       有能力者可以阅读日文题解(我觉得日文题解比英文题解好懂)。

       与えられた数 N が 10 進法で K 桁からなるとします。最上位の桁が c であるとすれば、 N 以下の正の整
数は、

       • 下から K 桁目は c 以下

       • それ以外の位は 9 以下

       です。よって、答えは c + 9(K − 1) 以下となります。

       また、答えが c + 9(K − 1) のとき、条件を満たす整数は c999···999 のみです。この値が N 以下となるような N は c999···999 の形をしているものしかありえないため、この場合のみ答えが c + 9(K − 1) となります。

       そうでない場合、整数 (c − 1)999···999 は N 以下で、各桁の和は c + 9(K − 1) − 1 となります。よって
これが最適で、すべての場合について答えが求まりました。

       時間計算量は O(logN) です。

       第一题可以算数学思维题,我们发现只有a999···999这样的最后结果就是所以位相加,否则就是(a-1)999···999的所有位上数字之和最大。应该显而易见。好了,发现了这一点就非常简单写出代码就可以了。

Code:

#include<iostream>
#include<cstring>
#include<cstdlib>
#include<algorithm>
#include<cmath>
#include<cstdio>
#define ll long long 
using namespace std;
inline int read()
{
	int x=0,f=1;char s=getchar();
	while(s<'0'||s>'9'){if(s=='-')f=-1;s=getchar();}
	while(s<='9'&&s>='0'){x=x*10+s-'0';s=getchar();}
	return x*f;
}
int main()
{
	char ch[50];
	scanf("%s",ch);
	bool flag=true;
	for(int i=1;i<strlen(ch);i++)
		if(ch[i]!='9')flag=false;
	if(flag)printf("%d\n",(strlen(ch)-1)*9+ch[0]-'0');else
		printf("%d\n",(strlen(ch)-1)*9+ch[0]-'0'-1);
	return 0;
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Jack-Oran

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值