Java program to check binary representation of the given number is palindrome or not

Given an integer number, we have to check binary representation of the number is palindrome or not.
Submitted by Nidhi, on March 10, 2022

Problem Solution:

In this program, we will read an integer number from the user. Then we will check binary representation of the given number is palindrome or not.

Program/Source Code:

The source code to check the binary representation of the given number is palindrome or not is given below. The given program is compiled and executed successfully.

// Java program to check binary representation of the 
// given number is palindrome or not

import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    Scanner SC = new Scanner(System.in);

    int num = 0;

    int c[] = new int[8];
    int i = 7;

    System.out.printf("Enter number between 0 to 255 : ");
    num = SC.nextInt();

    System.out.printf("Binary representation is: ");
    while (num != 0) {
      c[i--] = num & 1;
      num = num >> 1;
    }

    for (int j = 0; j < 8; j++)
      System.out.printf("%d", c[j]);
    System.out.printf("\n");

    for (int j = 0, k = 7; j < k; j++, k--) {
      if (c[j] != c[k]) {
        System.out.printf("Not palindrome\n");
        return;
      }
    }
    System.out.printf("it's palindrome\n");
  }
}

Output:

Enter number between 0 to 255 : 153
Binary representation is: 10011001
it's palindrome

Explanation:

In the above program, we imported "java.util.Scanner" package to read variables values from the user. And, created a public class Main. It contains a static method main().

The main() method is an entry point for the program. Here, we read an integer number from the user using the Scanner class and checked the binary representation of the given number is palindrome or not and printed the appropriate message.

Java Basic Programs »



Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.