How to Check if a Number is a Palindrome in C, Java, and Python – IQCode

Palindrome Number

A palindrome number is one that remains the same when its digits are reversed. For example, the number 12321 is a palindrome, while 1451 is not.

## Problem Statement

Given an integer, determine whether or not it is a palindrome.

## Dry run of the above approach

To check whether a number is a palindrome, we can use the following approach:

1. Initialize a variable `rev` to zero.
2. While the given number `n` is greater than zero, get its last digit by taking the modulus 10.
3. Multiply the variable `rev` by 10 and add the last digit.
4. Remove the last digit from the given number `n` by dividing it by 10.
5. Continue this process until `n` becomes zero.
6. If the final value of `rev` is equal to the original number, then it is a palindrome, otherwise it is not.

## Implementation

Here are the implementations of the palindrome number check algorithm in multiple programming languages:

### C/C++ Implementation

“`c
#include
int main()
{
int n, rev = 0, remainder, original;

printf(“Enter an integer: “);
scanf(“%d”, &n);

original = n;

// reversed integer is stored in variable
while (n != 0) {
remainder = n % 10;
rev = rev * 10 + remainder;
n /= 10;
}

// palindrome if orignal and reversed are equal
if (original == rev)
printf(“%d is a palindrome.”, original);
else
printf(“%d is not a palindrome.”, original);

return 0;
}
“`

“`cpp
#include
using namespace std;

int main()
{
int n, rev = 0, remainder, original;

cout << "Enter an integer: "; cin >> n;

original = n;

// reversed integer is stored in variable
while (n != 0) {
remainder = n % 10;
rev = rev * 10 + remainder;
n /= 10;
}

// palindrome if orignal and reversed are equal
if (original == rev)
cout << original << " is a palindrome."; else cout << original << " is not a palindrome."; return 0; } ``` ### Java Implementation ```java import java.util.Scanner; public class PalindromeNumber { public static void main(String[] args) { int n, rev = 0, remainder, original; Scanner sc = new Scanner(System.in); System.out.println("Enter an integer: "); n = sc.nextInt(); original = n; // reversed integer is stored in variable while (n != 0) { remainder = n % 10; rev = rev * 10 + remainder; n /= 10; } // palindrome if orignal and reversed are equal if (original == rev) System.out.println(original + " is a palindrome."); else System.out.println(original + " is not a palindrome."); } } ``` ### Python Implementation ```python n = int(input("Enter an integer: ")) rev = 0 original = n while n != 0: remainder = n % 10 rev = rev * 10 + remainder n //= 10 if original == rev: print(f"{original} is a palindrome.") else: print(f"{original} is not a palindrome.") ``` ## Special case In some cases, negative numbers and single-digit numbers also need to be considered for the palindrome check. Here is how the implementation would look: ### C Implementation of Special Case ```c #include
int main()
{
int n, rev = 0, remainder, original;

printf(“Enter an integer: “);
scanf(“%d”, &n);

original = n;

if (n < 0) { n = -n; } // reversed integer is stored in variable while (n != 0) { remainder = n % 10; rev = rev * 10 + remainder; n /= 10; } // palindrome if orignal and reversed are equal if (original == rev) printf("%d is a palindrome.", original); else printf("%d is not a palindrome.", original); return 0; } ``` ### C++ Implementation of Special Case ```cpp #include
using namespace std;

int main()
{
int n, rev = 0, remainder, original;

cout << "Enter an integer: "; cin >> n;

original = n;

if (n < 0) { n = -n; } // reversed integer is stored in variable while (n != 0) { remainder = n % 10; rev = rev * 10 + remainder; n /= 10; } // palindrome if orignal and reversed are equal if (original == rev) cout << original << " is a palindrome."; else cout << original << " is not a palindrome."; return 0; } ``` ### Java Implementation of Special Case ```java import java.util.Scanner; public class PalindromeNumber { public static void main(String[] args) { int n, rev = 0, remainder, original; Scanner sc = new Scanner(System.in); System.out.println("Enter an integer: "); n = sc.nextInt(); original = n; if (n < 0) { n = -n; } // reversed integer is stored in variable while (n != 0) { remainder = n % 10; rev = rev * 10 + remainder; n /= 10; } // palindrome if orignal and reversed are equal if (original == rev) System.out.println(original + " is a palindrome."); else System.out.println(original + " is not a palindrome."); } } ``` ### Python Implementation of Special Case ```python n = int(input("Enter an integer: ")) rev = 0 original = n if n < 0: n = -n while n != 0: remainder = n % 10 rev = rev * 10 + remainder n //= 10 if original == rev: print(f"{original} is a palindrome.") else: print(f"{original} is not a palindrome.") ``` ## Practice Question Write a program to find the largest palindrome made from the product of two n-digit numbers. ## Frequently Asked Questions ### Q.1: Can a negative number be palindrome? No, negative numbers cannot be palindromes, as reversing their digits would result in a different number. ### Q.2: Can we solve this problem without converting an integer to a string? Yes, we can solve this problem without converting an integer to a string, as shown in the code examples above. ### Q.3: Are all single-digit numbers palindrome? Yes, all single-digit numbers are palindromes. ### Q.4: How is the time complexity of the above algorithm O(log10(N))? The time complexity of the above algorithm is O(log10(N)), as the number of digits in the input integer `N` is proportional to the logarithm (base 10) of the number itself.

Check if a Number is Palindrome or Not

Given a positive integer, the program checks whether the number is a palindrome or not.

Example:

  • Input: 1221
    Output: True
  • Input: 146541
    Output: False
  • Input: 5
    Output: True

The program first initializes a variable called reversed_num to 0. It then loops through the given number, getting the last digit of the number in each iteration, and adds it to the end of reversed_num. Finally, it checks if the given number and reversed_num are equal or not.


def is_palindrome(number):
reversed_num = 0
temp_num = number

while temp_num > 0:
reversed_num = reversed_num * 10 + (temp_num % 10)
temp_num = temp_num // 10

return reversed_num == number

Reverse a Number

This program reverses a given integer number using an iterative approach. The reversed number is stored in a variable called reverseNum.


int original = 1221;
int reverseNum = 0;
int tempOriginal = original;

while (tempOriginal != 0) {
int lastDigit = tempOriginal % 10;
reverseNum = reverseNum * 10 + lastDigit;
tempOriginal /= 10;
}

if (reverseNum == original) {
System.out.println("The number " + original + " is a palindrome.");
} else {
System.out.println("The number " + original + " is not a palindrome.");
}

Check Palindrome Function in C++



bool isPalindrome(int num) {
int reverse_num = 0;
int temp_num = num;
while(temp_num > 0) {
int last_digit = temp_num % 10;
reverse_num = reverse_num * 10 + last_digit;
temp_num = temp_num / 10;
}
if(num == reverse_num) {
return true;
} else {
return false;
}
}

The above is a C++ function that checks whether a given number is a palindrome or not.

The function takes an integer as input and performs a reverse calculation on the input number and checks if it is equal to the original number, if so it returns true else false.

Java Implementation of Palindrome Number Check

This Java code checks whether a given number is a palindrome or not.

The implementation makes use of a while loop and some simple arithmetic operations.


public int checkPalindromeNumber(int num) {
    int reverseNum = 0;
    int tempNum = num;
    while (tempNum > 0) {
        int lastDigit = tempNum % 10;
        reverseNum = reverseNum * 10 + lastDigit;
        tempNum /= 10;
    }
    if (num == reverseNum) {
        return 1;
    } else {
        return 0;
    }
}

Call the function with an integer argument to determine if it is a palindrome number.

Function returns 1 if number is a palindrome, else returns 0.

Python Function to Check Palindrome Number

This Python function checks whether a given integer number is a palindrome number or not. It returns 1 if the number is a palindrome and 0 if it is not.


def check_palindrome(num):
reversed_num = 0
temp_num = num

# Reversing the number
while temp_num > 0:
last_digit = temp_num % 10
reversed_num = reversed_num * 10 + last_digit
temp_num //= 10

# Checking if the number is palindrome
if num == reversed_num:
return 1
else:
return 0

# Time complexity: O(log10(N)), where N is the given number.
# Space complexity: O(1)

The time complexity of this function is O(log10(N)), where N is the given number. The space complexity is O(1).

Solution for Large Numbers

If the number exceeds 10^18, the previous solution won’t work. In such a case, we can use a big integer data type or a string to store the number and perform arithmetic operations on its digits.Rewritten Code:

Check Palindrome Function in C

Code:

bool isPalindrome(char str[]) {

int length = strlen(str);

// compare the first and last characters of the string
// and move towards the middle until a mismatch is found
for (int i = 0; i < length / 2; i++) { if (str[i] != str[length - i - 1]) { return false; } } return true; } // Example usage int main() { char word[] = "deified"; // example palindrome word bool result = isPalindrome(word); if (result) { printf("%s is a palindrome", word); } else { printf("%s is not a palindrome", word); } return 0; } The given code is a C implementation of a function that checks if a string is a palindrome or not. I have fixed the variable names and added comments to make the code more understandable. The code is now optimized and concise, while maintaining the original functionality. The main function includes an example usage of the isPalindrome function.Checking Palindromes in C++

Palindrome Checker

Code:

“`
bool isPalindrome(string word) {
//get the length of the word
int length = word.size();

//iterate over the word to compare the first and last letters
for (int i=0; iJava Method to Check Palindrome

Code:

public boolean isPalindrome(String inputString) {
int length = inputString.length();

// Loop through each character of the string
for (int i = 0; i < length / 2; i++) { // Check if the leftmost character is equal to the rightmost character if (inputString.charAt(i) != inputString.charAt(length - i - 1)) { return false; } } return true; } /* This method accepts a string as input and returns a boolean value depending on whether the given string is a palindrome or not. A string is a palindrome if it reads the same from left to right as it does from right to left. */ This method checks whether a given string is a palindrome or not. It works by looping through each character of the string and comparing the leftmost character to the rightmost character. If any pair of characters does not match, the method returns false. Otherwise, it returns true if the string is a palindrome.

Python Implementation of Palindrome Checker


def is_palindrome(word):
"""
Accepts a string and checks if it's a palindrome.
:param word: str
:return: bool
"""
length = len(word)
for i in range(length // 2):
if word[i] != word[length - i - 1]:
return False
return True

# Time Complexity: O(n/2) => O(n), where n is the length of the given string
# Space Complexity: O(1)

The code checks if the given string is a palindrome or not. It takes a input string and loops through the first half of the string comparing it with the corresponding character from the end. If there is a mismatch, it returns False. If the loop completes without returning False, it returns True to indicate that the input string is a palindrome.

Checking for Palindrome Integer

This program checks if a given integer is a palindrome or not.

“`python
def is_palindrome(num):
# Convert integer to string and check if it matches with reversed string
return str(num) == str(num)[::-1]
“`

The above code makes use of Python’s built-in string slicing method to reverse the string representation of the integer and check if it matches the original string. This method returns `True` if the integer is a palindrome and `False` otherwise.

Example:
“`python
print(is_palindrome(121)) # Output: True
print(is_palindrome(123)) # Output: False
“`

This is a commonly asked interview question, so it’s important to be able to write this code efficiently and without errors.

Frequently Asked Questions

Can a Negative Number be a Palindrome?

No, it is not possible for a negative number to be a palindrome. A palindrome is a number that remains the same when its digits are reversed. In a negative number, the minus sign would be in the wrong place if the digits were reversed, making it not a palindrome.


// Code to check if a number is a palindrome
function isPalindrome(num) {
return num.toString() === num.toString().split('').reverse().join('');
}

Can we solve this problem without converting an integer to a string?

Yes, it is possible to solve this problem without converting an integer to a string, but it would depend on the size of the integer. For values less than 10^18, it can be solved without conversion.

// Example code for solving the problem without conversion for values less than 10^18

long long num = 123456789; // example integer value

// implementation of solution
if(num < 1000000000000000000){ // checking if integer is less than 10^18 // solve the problem here without converting the integer to a string }else{ // convert the integer to a string and then solve the problem string str_num = to_string(num); // solve the problem using the string value }

Are All Single-Digit Numbers Palindromes?

Yes, all single-digit numbers are palindromes because they are the same forwards and backwards. For example, 1, 2, 3, 4, 5, 6, 7, 8, and 9 are all palindromes.

//no code required

Time Complexity of Algorithm to Find Number of Digits in a Number

The time complexity of the above algorithm is O(log(N)) because we divide the input number N by 10 in each iteration. Therefore, there will be a maximum of log(N) iterations.


int countDigits(int n) {
int count = 0;
while (n != 0) {
n /= 10;
++count;
}
return count;
}

Top 10 Productivity Tools for Programmers

Best AngularJS Projects with Source Code for 2023 – IQCode

IQCode’s Top Android Projects with Source Code in 2023

15 Best Data Science Projects with Source Code – IQCode