Luke Skywalker gave Chewbacca an integer number x. Chewbacca isn't good at numbers but he loves inverting digits in them. Inverting digit t means replacing it with digit 9 - t.
Help Chewbacca to transform the initial number x to the minimum possible positive number by inverting some (possibly, zero) digits. The decimal representation of the final number shouldn't start with a zero.
The first line contains a single integer x (1 ≤ x ≤ 1018) — the number that Luke Skywalker gave to Chewbacca.
Print the minimum possible positive number that Chewbacca can obtain after inverting some digits. The number shouldn't contain leading zeroes.
27
22
4545
4444
题意:给出一个数字,对这个数字的每一位都可以有两个操作:保持原数字,或者翻转(用9减该位数字)。求最后求出来的数字的最小值。
思路:简单贪心,只需要每一位数字都最小,则整个数字肯定最小。对每一位数字都取 min(a, 9-a)就ok了,非常简单,但我用字符串做的时候,总是输出不了样例。
错误代码:
for(int i = 0; i < s.size(); ++i)
s[i] = min(s[i], '9'-s[i]);
cout << s << endl;
错误原因:对ASCII码不够熟悉,'9'-s[i] 得出来的是 数字 1 2 3 4 5 .... 而不是字符 ‘1’‘2’,所以还应该改为
s[i] = min(s[i], '9'-s[i]+'0')
代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <algorithm>
#include <vector>
#include <queue>
#include <stack>
#include <cmath>
#include <map>
#include <set>
using namespace std;
const int INF = 0x7fffffff;
int main()
{
char s[20];
cin >> s;
int n = strlen(s);
for(int i = 0; i < n; ++i)
{
if(i == 0 && s[i] == '9')
continue;
else
{
if(s[i] >= '5')
s[i] = '9'- s[i] +'0';
else
continue;
}
}
cout << s << endl;
return 0;
}