微软笔试-Numberic Keypad

题目描述

The numberic keypad on your mobile phone looks like below: 123 456 789 0 suppose you are holding your mobile phone with single hand. Your thumb points at digit 1. Each time you can 1)press the digit your thumb pointing at.2)moveyour thumb right,3)move your thumb down. Moving your thumb left or up is not allowed. By using the numeric keypad under above constrains, you can produce some numbers like 177 or 480 while producing other numbers like 590 or 52 is impossible. Given a number K, find out the maximum number less than or equal to K that can be produced. 输入描述: the first line contains an integer T, the number of testcases. Each testcase occupies a single line with an integer K. For 50%of the data ,1<=K<=999. For 100% of the data, 1<=K<=10^500,t<=20. 输出描述: for each testcase output one line, the maximum number less than or equal to the corresponding K that can be produced. 输入例子: 3 25 83 131 输出例子: 25 80 129

思路:

给定一个数,依次判断数的每一位,看该位的后一位能否放到该位的后边,
1、若是可以放到给位的后边,则继续编辑
2、若是不能放到该位的后边:需要找到能放到该位后边,且小于当前数的最大的一个数
	若是找到,则该位变为符合要求的最大值,然后将其后的所有值全部变为9。
	若是找不到,则将该位的值减1,然后将其后的所有值全部变为9。重复判断该位修改之后能否放在该位,即该位的前一位是否能容纳该位的值
以样例来说明:
131  首先看第1位,看第2位能否放到第1位后边,第2位为3,可以放到该位
     接着看第2位,看第3位能否方法哦第2位后边, 第三位为1, 不能放到第2位后边,查找能放到第2位的书中数,没有小于1的
		则将第2位的数字减1,并将第三位设置为9。 重复判断第2位能否放到第1位后边
    继续看第2位,此时为2, 可以放到第一位后边
    看第3位,此时为9, 可以放到第2位后边。
    结束。


代码:

# -*- coding:utf-8 -*-
import  sys

def getMaxNum(k,nDict):
    nums = [int(i) for i in list(k)]
    lens = len(nums)
    i = 0
    while i< lens-1:
        if nums[i+1] not in nDict[nums[i]]:
            tpIndex = len(nDict[nums[i]])-1
            while tpIndex >=0 and nDict[nums[i]][tpIndex]> nums[i+1]:
                tpIndex -=1
            if tpIndex !=-1:
                nums[i+1] = nDict[nums[i]][tpIndex]
                nums[i+2:lens] = [9] *(lens-i-2)
                i+=1
            else:
                nums[i]-=1
                nums[i + 1:lens] = [9] * (lens - i - 1)
                i = i-1 if i>0 else i
        else:
            i+=1
    res = 0
    for i in nums:
        res = res*10+i
    return res

if __name__ == '__main__':
    while True:
        t = sys.stdin.readline().strip()
        if not t:
            break
        t = int(t)
        nDict = {}
        nDict[1] = [0,1, 2, 3, 4, 5, 6, 7, 8, 9]
        nDict[2] = [0,2, 3, 5, 6, 8, 9]
        nDict[3] = [3, 6, 9]
        nDict[4] = [0,4, 5, 6, 7, 8, 9]
        nDict[5] = [0,5, 6, 8, 9]
        nDict[6] = [6, 9]
        nDict[7] = [0,7, 8, 9]
        nDict[8] = [0,8, 9]
        nDict[9] = [9]
        nDict[0] = [0]
        for i in range(t):
            k = sys.stdin.readline().strip()
            print getMaxNum(k,nDict)







评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值