检查Java中的值是否是旋转对称的

时间:2016-11-15 20:20:08

标签: java

我最近在电话采访中被问到了这个问题。给定一个值,检查它是否旋转对称。旋转对称意味着,如果我们在页面上写下该数字并将该页面旋转180º,则数字保持不变。 我回答了下面的解决方案,并想知道是否有更好的方法来做到这一点。谢谢!

import java.util.HashMap;

public class Rotational_Symmetric {

    public static void main(String args[]){
        HashMap<Character,Character> numbers = new HashMap<>();
        numbers.put('0', '0');
        numbers.put('1', '1');
        numbers.put('6', '9');
        numbers.put('8', '8');
        numbers.put('9', '6');

        System.out.println(isRotationallySymmetric(numbers,"0891680")); //true
        System.out.println(isRotationallySymmetric(numbers," ")); //true
        System.out.println(isRotationallySymmetric(numbers,"169")); //false
        System.out.println(isRotationallySymmetric(numbers,"8")); //true
        System.out.println(isRotationallySymmetric(numbers,"5")); //false
    }

    //to check if a value is rotationally symmetric
    //consider example "0891680"

    public static boolean isRotationallySymmetric(HashMap numbers, String input){
        if(input == null || input.equals(" ")){
            return true;
        }

        if(input.equals("2") || input.equals("3")||input.equals("4") 
                || input.equals("5") || input.equals("7")){
            return false;
        }

        char[] charInput = input.toCharArray();
        int start = 0;
        int end = input.length()-1;
        while(start<end){
            if(charInput[start] == (char)numbers.get(charInput[end])){
                start++;
                end--;
                continue;
            }
            else{
                return false;
            }
        }
        return true;
    }
}

0 个答案:

没有答案