Check if number is palindrome or not in Octal in Python


Suppose we have a number which is either in octal or in decimal form. If this is in octal form check whether it is palindrome or not. If the number in decimal, then convert it to octal then check whether it is palindrome or not.

So, if the input is like num = 178, then the output will be True as the number is not in octal form (8 is not valid symbol in octal but valid in decimal), then convert it to octal which is 262 and this is palindrome.

To solve this, we will follow these steps −

  • base := 8 when all digits of num is below 8, otherwise 10
  • oct_list := a new list
  • while num is not 0, do
    • insert (num mod base) at the end of oct_list
    • num := quotient of (num / base)
  • j := size of oct_list - 1
  • k := 0
  • while k <= j, do
    • if oct_list[j] is not same as oct_list[k], then
      • return False
    • j := j - 1, k := k + 1
  • return True

Example

Let us see the following implementation to get better understanding −

 Live Demo

def is_all_under_8(num):
   while num:
      if (num % 10) >= 8:
         return False
      else:
         num = int(num / 10)
      return True
def solve(num):
   base = 8 if(is_all_under_8(num) == False) else 10
   oct_list = []
   while num != 0:
      oct_list.append(num % base)
      num = int(num / base)
   j = len(oct_list)-1
   k = 0
   while k <= j:
      if oct_list[j] != oct_list[k]:
         return False
      j-=1
      k+=1
   return True
num = 178
print(solve(num))

Input

178

Output

True

Updated on: 19-Jan-2021

399 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements