2011-11-22 97 views
-1

我必须编写一个程序在java(家庭作业),给出输入(x),在二进制输入,告诉如果输入是回文,并告诉如果从输入二进制是一个回文。我可能不会使用除System.out.print之外的其他api,并且我可能不会使用字符串。Java十进制到二进制没有API和字符串

到目前为止好:我已经编写了程序,它的工作原理是x = 1023(因为int)。我必须编辑哪一段代码,所以输入可以是任何正数?

class Palindromes { 
public static int DtoBinary(int x) { 
    int y = x; 
    int w = 1; 
    int v = 0; 
    int z = 1; 
    int u = 0; 
    while (z < y) { 
     z = z * 2; 
     u++; 
    } 
    z = z/2; 
    for (int t=1; t<u; t++) { 
     w = 10 * w; 
    } 
    v = v + w; 
    y = y - z; 
    while (y > 0) { 
     z = z/2; 
     if (z <= y) { 
      w = w/10; 
      v = v + w; 
      y = y - z; 
     } else if (y == 1) { 
      v = v + 1; 
      y = 0; 
     } else { 
      w = w/10; 
      v = v + 0; 
     } 
    } 
    return v; 
} 

public static boolean Palindrome(int x) { 
    int s = x; 
    int r = 0; 
    while (s > 0) { 
     int q = s % 10; 
     r = r * 10 + q; 
     s = s/10; 
    } 
    if (x == r) { 
     return true; 
    } else { 
     return false; 
    } 
} 

public static void main(String[] args) { 
    int x = 1023; 

    System.out.print(x + " " + DtoBinary(x)); 
    if (Palindrome(x)) { 
     System.out.print(" yes"); 
    } else { 
     System.out.print(" no"); 
    } 
    if (Palindrome(DtoBinary(x))) { 
     System.out.print(" yes"); 
    } else { 
     System.out.print(" no"); 
    } 
} 
} 
+0

我试图使用长而不是int的v和w,但后来我得到一个错误,返回值必须是int。 – Waarten

+0

你想在启动程序时指定一个数字吗? – hellectronic

+0

@hellectronic不,int x = ...;部分就够了。 – Waarten

回答

-1

我可以为作业提供简短的解决方案。

public static boolean isPalindrome(int x) { 
    String inputted = "" + x; 
    String reverse = new StringBuffer(inputted).reverse().toString();  

    return inputted.equals(reverse); 
} 

public static boolean isPalindrome(int x) { 
    String inputted = "" + x; 
    int length = inputted.length; 
    for(int i = 0; i< inputted/2; i++){ 
     if(inputted.charAt(i)!= inputted.charAt(inputted - 1 - i)){ 
      return false; 
     } 
    } 

    return true; 
} 
+0

“我可能不会使用api的System.out.print以外,我可能不会使用字符串。” –

0

您可以使用一个字符数组,而不是一个int来存储大量的二进制数为您的回文类。

public static char[] DtoBinary(int x) { 
    <insert code to convert x to an array of zeroes and ones> 
} 

您需要编写一个方法来检查char数组是否是回文。

相关问题