2015-05-26 40 views
1

我正在尝试编写程序来查找所有双位数的颠倒。其实我已经写了这个代码,它的工作也很好。任何其他替代方法可以找到整数的颠倒。说18 = 81和96 = 69 ....如何查找颠倒的2位数

List <Integer> al = new ArrayList <Integer>(); 

al.add(10);al.add(11);al.add(16);al.add(18);al.add(19);al.add(60);al.add(61); 
al.add(66);al.add(69);al.add(80);al.add(81);al.add(86);al.add(88);al.add(91); 
al.add(96);al.add(98);al.add(99); 

Scanner s = new Scanner(System.in); 
Integer n = s.nextInt(); 
if (((String)"" + n).length() == 2) { 
    if (al.contains(n)) 
     System.out.println("yes"); 
    else 
     System.out.println("no"); 
} 
+0

“n”与“颠倒”比较的部分在哪里? – Incognito

+0

n是我从输入中得到的数字。我比较n(运行时计算颠倒值的值)与ArrayList进行比较。 –

+0

我有点困惑。假设我输入了“18”,是的,它的长度是2,是“al”包含它。所以输出是'是'。涉及“81”的部分在哪里?或者你的代码仍然不完整? – Incognito

回答

3

这是一个简单的,一般的算法分析的整数w.r.t.数字与垂直对称。 (这取决于书写数字某种风格;请注意,“大陆”“1”不是对称的。)

private static int[] other = new int[]{0, 1, -1, -1, -1, -1, 9, -1, 8, 6}; 
public static int invert(int n){ 
    int units = n % 10; 
    n /= 10; 
    int inv = other[units]; 
    if(n == 0) return inv; 
    return inv < 0 ? -1 : invert(n)*10 + inv; 
} 

如果返回负值,数量不是对称的。

public static void main(String[] args) throws Exception { 
    for(int i = 100; i <= 199; ++i){ 
     int invi = invert(i); 
     if(invi > 0){ 
      System.out.println(i + ": " + invi); 
     } 
    } 
} 
0

这是一个更好的方法。 它不仅打印yes或no,而且上下颠倒数

public static void main(String[] args) { 

    List<String> al = new ArrayList<String>(); 
    al.add("0"); 
    al.add("1"); 
    al.add("6"); 
    al.add("8"); 
    al.add("9"); 

    Scanner s = new Scanner(System.in); 
    Integer n = s.nextInt(); 
    String num = n + ""; 

    if (num.length() == 2) { 
     if(al.contains(num.charAt(0) + "") && al.contains(num.charAt(1) + "")) { 
      System.out.println("Yes"); 

      String upSideDownNumber = ""; 
      if(num.charAt(1) == 6) { 
       upSideDownNumber += 9; 
      } else if(num.charAt(1) == 9) { 
       upSideDownNumber += 6; 
      } else { 
       upSideDownNumber += num.charAt(1); 
      } 

      if(num.charAt(0) == 6) { 
       upSideDownNumber += 9; 
      } else if(num.charAt(0) == 9) { 
       upSideDownNumber += 6; 
      } else { 
       upSideDownNumber += num.charAt(0); 
      } 

      System.out.println("The up side down number is " + upSideDownNumber); 

     } else { 
      System.out.println("No"); 
     } 


    } else { 
     System.out.println("No"); 
    } 
} 
0

由于倒数时只有0,1,6,8,9看起来像数字。您可以如下所示:

public static void main(String[] args) throws IOException { 
    Set<Integer> upsideDownProperDigits = new TreeSet<>(Arrays.asList(0,1,8,9,6)); 
    Scanner s = new Scanner(System.in); 
    Integer n = s.nextInt();  
    boolean found = true; 
    while(n != 0){ 
     int digit = n % 10; 
     if(!upsideDownProperDigits.contains(digit)){ 
      found = false; 
      break; 
     } 
     n = n/10; 
    } 
    if(found){ 
     System.out.println("yes"); 
    } 
    else{ 
     System.out.println("no"); 
    } 
}