-1

I must write a program in java (homework) that gives the input (x), the input in binary, tells if the input is a palindrome and tells if the binary from the input is a palindrome. I may not use api's other than System.out.print and I may not use strings.

So far so good: I've written the program and it works till x = 1023 (because of the int). Which piece of code must I edit, so the input can be any positive number?

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");
    }
}
}
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Waarten
  • 115
  • 6

2 Answers2

0

You can use a char array instead of an int to store large binary numbers for your palindrome class.

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

You will need to write a method that checks if a char array is a palindrome.

Klas Lindbäck
  • 33,105
  • 5
  • 57
  • 82
-1

I can offer short solution for homework.

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

     return inputted.equals(reverse);
}

or

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;
}
Sergey Gazaryan
  • 1,013
  • 1
  • 9
  • 25