Numeric Keypad

来源:互联网 发布:Mac笔记本可以连接Pc吗 编辑:程序博客网 时间:2024/06/06 20:07

题目描述

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 thumbpoints at digit 1. Each time you can 1)press the digit your thumbpointing at.2)moveyour thumb right,3)move your thumb down. Moving yourthumb left or up is not allowed.
 By using the numeric keypad under above constrains, you can producesome numbers like 177 or 480 while producing other numbers like 590 or52 is impossible.
 Given a number K, find out the maximum number less than or equal to Kthat 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.

输入例子:
32583131

输出例子:
2580129

参考到了一个大神的答案,自己改了改,结果就是折腾了半天,各种零碎各种改……(筋疲力尽ing)

代码如下:

import java.util.*;public class Main {public static void main(String[] args) {Scanner s = new Scanner(System.in);        int n = s.nextInt();        String[] str = new String[n];        s.nextLine();        for(int i=0; i<n; i++)            str[i] = s.nextLine();        for(int i=0; i<n; i++) {            String data = str[i];            char[] num = data.toCharArray();            for(int j=0; j<data.length()-1; j++) {                //不合适的那个结点        while(!reach(num[j], num[j+1])) {                    num[j+1]--;                    if(num[j+1]<'0') {                        num[j]--;                        if(j==0)                        num[j+1] = '9';                        else                        j--;                    }                    if(num[j+1]==0)                        for(int k=j+2; k<data.length(); k++)                            num[k] = '0';                    else {                        for(int k=j+2; k<data.length(); k++)                            num[k] = '9';                    }            }                }            }            for(int i2=0; i2<data.length(); i2++) System.out.print(num[i2]);            System.out.println();        }    }public static boolean reach(char first, char next) {        int row1=0, row2=0, col1=0, col2=0;        if(first=='0') {            first = '9'+'2';         }        if(next=='0')            next = '9'+'2';        row1 = (first-1-'0')/3;        col1 = (first+2-'0')%3;        row2 = (next-1-'0')/3;        col2 = (next+2-'0')%3;        if(row1<=row2 && col1<=col2)            return true;        return false;    }    }

心累到不想说话,就先这样吧……有时间把另一种方法做一做……

同学想到的是从低位到高位遍历判断,想法也不错,虽然有些情况下有点麻烦(数据大且问题只出在前几位的时候),但是可读性比较好,主要是不需要在低位借位变化后回过头再去看前面的是否受影响(很容易受影响……),具体的就不写了……


0 0
原创粉丝点击