Maximize Sum of Digits(思维)

题目链接:http://codeforces.com/contest/770/problem/B

Anton has the integer x. He is interested what positive integer, which doesn't exceed x, has the maximum sum of digits.

Your task is to help Anton and to find the integer that interests him. If there are several such integers, determine the biggest of them.

Input

The first line contains the positive integer x (1 ≤ x ≤ 10^18) — the integer which Anton has.

Output

Print the positive integer which doesn't exceed x and has the maximum sum of digits. If there are several such integers, print the biggest of them. Printed integer must not contain leading zeros.

Examples

Input

100

Output

99

Input

48

Output

48

Input

521

Output

499

求1~x范围内个位数之和最大的那个数(如果有多个,输出最大的那个数)

思路:比赛的时候是从后往前找,逢8或9不向前借位(8向前借一位,位数之和没变,但是数小了),其他的向前借位,并更新为9(应该把后面的都更新为9,就这样wa了5发,自闭)

其实这道题从前往后扫要简单太多,从第二高位开始扫(因为可能要借位),只要不是9,就从前一位借1,然后把后面的所有数都更新为9,break;   这样就保证了这个数不大于X,且其各位数之和一定是最大(但不一定是最大的那个,从前面借了1,但是后面也只加了1,比如48,输出应该是48,而不是39)

算出X的各位数之和与现在这个数的各位数之和,如果相等输出X,否则输出现在这个数

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cmath>
#include<string>
#include<cstring>
#include<map>
#include<vector>
#include<set>
using namespace std;
int a[25];
int b[25];
int solve(long long x) {
	int pos=0;
	while(x) {
		a[++pos]=x%10;
		x/=10;
	}
	return pos;
}
int main() {
	long long n;
	while(~scanf("%I64d",&n)) {
		int t=solve(n);
		for(int i=1; i<=t; i++)
			b[i]=a[i];
		for(int i=t-1; i>=1; i--) {
			if(b[i]!=9) {
				b[i+1]--;
				for(int j=i; j>=1; j--)
					b[j]=9;
				break;
			}
		}
		long long m=0;
		for(int i=t; i>=1; i--)
			m=m*10+b[i];
		int sum1=0;
		for(int i=t; i>=1; i--)
			sum1+=a[i];
		int sum2=0;
		for(int i=t; i>=1; i--)
			sum2+=b[i];
		long long ans;
		if(sum1>=sum2) ans=n;
		else ans=m;
		printf("%I64d\n",ans);
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_42936517/article/details/88386633