java输入整数最近的对称数,找出最接近的对称数字

找出几个候选答案然后比较差值(最多为4个)

长度为1,#长度为1,直接减一返回

开头为1,9~~9为一个候选答案 例:100001,答案为99999

开头为9,10~~01为一个候选答案 例:99999,答案为100001

如果本身对称,则把最中间的一个(或两个)位数减(如果0则加)一

例:123321,答案为122221

例:120021,答案为121121

如果不对称:

-把前半部分逆序替换掉后半部分 例:1223,答案为1221

-把最中间的一个(或两个)位数加一 例:1291,答案为1331,而非1221

-把最中间的一个(或两个)位数减一 例:1800,答案为1771,而非1881

额外的,在这里测试用例比较少,有些情况并未测试出来。如果本身不对称直接把前半部分逆序替换掉后半部分也是能通过的。但不严谨。希望添加测试用例。

例:9, 答案为8(没有单个数的测试用例)

例:1291,答案为1331,而非1221

例:1800,答案为1771,而非1881

while True:

try:

string = input()

length = len(string)

if length == 1: # 长度为1,直接减一

print(str(int(string) - 1))

else:

candidate = [] # 候选字答案

if string[0] == '1': # 开头为1,9**9可能为候选字

candidate.append('9' * (length - 1))

elif string[0] == '9': # 开头为9,10**01可能为候选字

candidate.append('1' + '0' * (length - 1) + '1')

if string == string[::-1]: # 如果本身对称,则把最中间的一个(或两个)位数减(如果0则加)一

temp = list(string)

if temp[length // 2] == '0':

temp[length // 2] = temp[(length - 1) // 2] = '1'

else:

char = str(int(temp[length // 2]) - 1)

temp[length // 2] = temp[(length - 1) // 2] = char

candidate.append(''.join(temp))

else: # 不对称,把前半部分逆序替换掉后半部分

temp = list(string[:(length // 2)] + string[:((length + 1) // 2)][::-1])

candidate.append(''.join(temp))

if temp[length // 2] == '0': # 最中间为0,只能加一

temp[length // 2] = temp[(length - 1) // 2] = '1'

candidate.append(''.join(temp))

elif temp[length // 2] == '9': # 最中间为9,只能减一

temp[length // 2] = temp[(length - 1) // 2] = '8'

candidate.append(''.join(temp))

else: # 加一和减一都加入候选答案

char = int(temp[length // 2])

temp[length // 2] = temp[(length - 1) // 2] = str(char + 1)

candidate.append(''.join(temp))

temp[length // 2] = temp[(length - 1) // 2] = str(char - 1)

candidate.append(''.join(temp))

candidate = sorted(list(map(int, candidate)))

string = int(string)

diff = string # 保存差值

for num in candidate: # 在候选答案里选择差值最小的最小数(前面已排序)

if abs(string - num) < diff:

result = num

diff = abs(string - num)

print(result)

except Exception:

break

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值