题目:
B. Anton and currency you all know
time limit per test
0.5 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output
Berland, 2016. The exchange rate of currency you all know against the burle has increased so much that to simplify the calculations, its fractional part was neglected and the exchange rate is now assumed to be an integer.
Reliable sources have informed the financier Anton of some information about the exchange rate of currency you all know against the burle for tomorrow. Now Anton knows that tomorrow the exchange rate will be an even number, which can be obtained from the present rate by swapping exactly two distinct digits in it. Of all the possible values that meet these conditions, the exchange rate for tomorrow will be the maximum possible. It is guaranteed that today the exchange rate is an odd positive integer n. Help Anton to determine the exchange rate of currency you all know for tomorrow!
Input
The first line contains an odd positive integer n — the exchange rate of currency you all know for today. The length of number n's representation is within range from 2 to 105, inclusive. The representation of n doesn't contain any leading zeroes.
Output
If the information about tomorrow's exchange rate is inconsistent, that is, there is no integer that meets the condition, print - 1.
Otherwise, print the exchange rate of currency you all know against the burle for tomorrow. This should be the maximum possible number of those that are even and that are obtained from today's exchange rate by swapping exactly two digits. Exchange rate representation should not contain leading zeroes.
单词:currency n.货币。 fractional adj.部分的。 inclusive. adj.包含的
题意:有一个字符串,里面都是数字,且为奇数,问能不能变成偶数,能的活则输出所有情况中最大的一种情况,不能的话就输出-1
思路:利用ascii码先将字符串中的字符数字类型转化为int类型的数字,且放进vector里面,将最后一个数字与第一个位置比较,如果是偶数,且不是最后一个偶数,判断两个数大小,如果最后的数大,则和下一个数比较,直到出现比最后一个数大的偶数,或者直到最后一个偶数出现,交换值,输出,结束。
#include <iostream>
#include<algorithm>
#include<string>
#include<vector>
using namespace std;
bool judgeEvenNumber(int a)
{
if (a&1)
{
return false;
}
return true;
}
int main(int argc, const char * argv[])
{
//题意:有一个字符串,里面都是数字,且为奇数,问能不能变成偶数,能的活则输出所有情况中最大的一种情况,不能的话就输出no
int index=0;//记录偶数出现的次数
string s;
cin>>s;
int len=s.length();
vector<int>v;
for (int i=0; i<len; i++)
{
int x;
x=(int)s[i]-48;
v.push_back(x);
if (judgeEvenNumber(x))
{
index++;
}
}
if (index==0)
{
cout<<-1;
return 0;
}
for (int i=0; i<len-1; i++)//1)找偶数
{
if (judgeEvenNumber(v[i]))
{
int temp;
index--;
if (index==0)
{
temp=v[i];
v[i]=v[len-1];
v[len-1]=temp;
break;
}
else
{
if (v[i]<v[len-1])
{
temp=v[i];
v[i]=v[len-1];
v[len-1]=temp;
break;
}
}
}
}
for (int i=0; i<len; i++)
{
cout<<v[i];
}
return 0;
}