2016 Winter Training Day #1_E题_codefcrces 514A(贪心)

A. Chewbaсca and Number
time limit per test
 1 second
memory limit per test
 256 megabytes
input
 standard input
output
 standard output

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.

Input

The first line contains a single integer x (1 ≤ x ≤ 1018) — the number that Luke Skywalker gave to Chewbacca.

Output

Print the minimum possible positive number that Chewbacca can obtain after inverting some digits. The number shouldn't contain leading zeroes.

Sample test(s)
input
27
output
22
input
4545
output

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值