Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
Check if binary representation of a number is palindrome in Python
Suppose we have a number n. We have to check whether the binary representation of n is palindrome or not.
So, if the input is like n = 9, then the output will be True as binary representation of 9 is 1001, which is palindrome.
To solve this, we will follow these steps −
- ans := 0
- while num > 0, do
- ans := ans * 2
- if num is odd, then
- ans := ans XOR 1
- num := num / 2
- return ans
Let us see the following implementation to get better understanding −
Example
def reverse_binary(num) : ans = 0 while (num > 0) : ans = ans << 1 if num & 1 == 1 : ans = ans ^ 1 num = num >> 1 return ans def solve(n) : rev = reverse_binary(n) return n == rev n = 9 print(solve(n))
Input
9
Output
True
Advertisements
