Given a number, write a algorithm, flowchart, pseudocode to check if it is palindrome or not.
A string is said to be palindrome if reverse of the string is same as string. For example, 1221 is palindrome, but 1223 is not palindrome.
We will follow a method where we get each numbers using mathematical operations.
Logic
-
Get the number to check and store it in
n. -
Create empty variables
r = 0,s = 0andt = n. Here,swill become the reversed number,twill be a reference to original number,rwill be a temporary variable. -
Start a while loop checking whether the
n != 0(if n is 0 exit the while loop). -
Inside the while loop do the following operations.
r = n % 10 s = s * 10 + r n = n / 10First get the last digit of
nby dividing the given number(n) by 10 and finding the remainder(the%operator) and store it inr. Then, addrtosafter multiplying it by previous stored value ofsby 10. And finally dividenby 10 and store it again inn. This way the number is reversed and stored ins. -
After the loop ends, check whether
s == t(whether the original number is same as reversed number). -
If
s == t, display thatnpalindrome, else displaynis not a palindrome.
Flowchart
WIP, have a look here.
graph TD
A((Start)) --> B[/Read Number to check as n/];
B --> C[Assign s=0, t = n];
C --> D{ While n!=0 };
D -- True --> E["r = n % 10 <br>s = s * 10 + r<br>n = n / 10"] --> D
D -- False --> F{Is n == t?}
F -- Yes --> G[/Print n is palindrome/] --> I[Stop];
F -- No --> H[/Print n is not a palindrome/] --> I((Stop));Pseudocode
BEGIN
READ number to check as n
SET s = 0
SET t = n
WHILE n != 0 DO
r = n % 10
s = s * 10 + r
n = n / 10
ENDWHILE
IF n == t
DISPLAY n is palindrome
ELSE
DISPLAY n is not a palindrome
ENDIF
ENDImplementation
-
In C:
#include <stdio.h> /* Function to check if n is Palindrome*/ int is_palindrome(int n) { int s = 0; int t = n; int r = 0; while (n != 0 ) { r = n % 10; s = s * 10 + r; n = n / 10; } // Check if rev_n and n are same or not. if (s == t) return 1; else return 0; } int main() { int tocheck = 1221; int op = is_palindrome(to_check); if (op == 1) printf("%d is a palindrome", tocheck); else printf("%d is not a palindrome", tocheck); return 0; } -
In Python:
def is_palindrome(n: int) -> bool: s = 0 t = n r = 0 while n != 0: r = n % 10 s = s * 10 + r n = n / 10 if t == s: return True else: return False number = 1001 palim = is_palindrom(number) if palim: print(f"{number} is a palindrom") else: print(f"{number} is not a palindrom")
