Today’s algorithm problem is to solve the "Palindrome Number" algorithm using C language. Here is my thought process and implementation, let’s take a look.
Algorithm Problem
Given an integer, determine if it is a palindrome number. A palindrome number is an integer that reads the same forwards and backwards.
Algorithm Idea
We will use a digit-by-digit comparison method to solve the palindrome number problem.
The steps of the algorithm are as follows:
If the given integer is negative, return false immediately.
Initialize a variable <strong>reversed</strong> to 0, which will store the reversed integer.
Loop through the following steps until the given integer is 0:
-
Get the last digit of the given integer (by taking modulo 10).
-
Multiply reversed by 10 and add the last digit.
-
Divide the given integer by 10 and round down.
If reversed is equal to the original integer, return true; otherwise, return false.
👇Click to receive👇
👉C Language Knowledge Resource Collection
Code Implementation
Here is a sample code for implementing the “Palindrome Number” algorithm in C language:
#include <stdbool.h>
bool isPalindrome(int x) { if (x < 0) return false;
int reversed = 0; int original = x;
while (x != 0) { int digit = x % 10; reversed = reversed * 10 + digit; x /= 10; }
return (reversed == original);
}
Algorithm Analysis
The time complexity of this algorithm is O(log(x)), where x is the number of digits in the given integer. In the loop, we divide the given integer by 10 each time, so the number of iterations depends on the number of digits in the given integer.
The space complexity is O(1).
Examples and Tests
Example Input 1:
Input: 121
Example Output 1:
true
Example Input 2:
Input: -121
Example Output 2:
false
Example Input 3:
Input: 10
Example Output 3:
false
Example Input 4:
Input: 12321
Example Output 4:
true
Conclusion
This article provides a solution to the palindrome number problem using C language. By comparing the digits of the integer in both forward and reverse order, we can determine whether an integer is a palindrome number. The time complexity of this algorithm is O(log(x)), and the space complexity is O(1).
Programmer Technical Communication Group
Scan the code to join the group, remember to note: city, nickname, and technical direction.