次方自己寫的原因是math.h的回傳是double,位數好像會不夠
我的想法是從最高位往下直到看到第一個偶數,然後分兩個可能的答案,第一個是把看到的第一個偶數+1,後面全部改成1;第二個是把看到的第一個偶數-1,後面全部改成9。
還有Sec_Is_0是為了避免10XX開頭的狀況,因為她的答案可能是9XX
valid1、valid2 是確認 第一個偶數可能是0,然後被減一變成-1的狀況
可以的話,麻煩幫我看一下為什麼#1,#2,#3會WA
//我的程式碼
#include<iostream>
#include<vector>
#include<math.h>
using namespace std;
uint64_t pow10(int x,int y)
{
uint64_t o = 1;
int f = x;
unsigned int k = y;
while (k != 0) {
if (k % 2 == 1) o *= f;
k >>= 1;
f *= f;
}
return o;
}
int main()
{
uint64_t in;
while (cin>>in)
{
long long b = in;
bool is = false;
bool Sec_Is_0 = false;
bool valid1 = true;
bool valid2 = true;
vector<int> digit;
vector<int> ans1;
vector<int> ans2;
while (in != 0)
{
int t = in % 10; digit.push_back(t);
in /= 10;
}
if (digit.size() > 1) { if (digit[1] == 0) { Sec_Is_0 = true; } }
for (int i = digit.size() - 1; i >= 0; i--)
{
if (is) { ans1.push_back(1); ans2.push_back(9); continue; }
if ((digit[i] % 2)== 0)
{
is = true; ans1.push_back(digit[i] + 1); if ((i == digit.size() - 2) && Sec_Is_0) { ans2[0]=9; }
else { ans2.push_back(digit[i] - 1); }; continue;
}
ans1.push_back(digit[i]); ans2.push_back(digit[i]);
}
uint64_t a1 = 0;
uint64_t a2 = 0;
uint64_t answer1 = 0;
uint64_t answer2 = 0;
for(int i=0;i<ans1.size();i++)
{
if (ans1[i]<0) { valid1 = false; break; }
a1 += ans1[i]*pow10(10, ans1.size() - 1-i);
}
for (int i = 0; i < ans2.size(); i++)
{
if (ans2[i] < 0) {valid2 = false;break; }
a2 += ans2[i] * pow10(10, ans2.size() - 1-i);
}
if (a1 > b) { answer1 = a1 - b; }
else { answer1 = b- a1; }
if (a2 > b) { answer2 = a2 - b; }
else { answer2 = b - a2; }
if (valid1 && valid2)
{
if (answer1 > answer2) { cout << answer2 << endl; }
else { cout << answer1 << endl; }
}
else
{
if (valid1) { cout << answer1 << endl; }
else { cout << answer2 << endl; }
}
}
}