Go Program to Check Palindrome Number
if original == reversed { fmt.Println("Palindrome") }.Examples
How to Think About It
Algorithm
Code
package main import "fmt" func main() { var num, original, reversed, digit int fmt.Print("Enter a number: ") fmt.Scan(&num) original = num reversed = 0 for num > 0 { digit = num % 10 reversed = reversed*10 + digit num /= 10 } if original == reversed { fmt.Printf("%d is a palindrome number\n", original) } else { fmt.Printf("%d is not a palindrome number\n", original) } }
Dry Run
Let's trace the number 121 through the code to see how it checks palindrome.
Initialize variables
num=121, original=121, reversed=0
First loop iteration
digit = 121 % 10 = 1; reversed = 0*10 + 1 = 1; num = 121 / 10 = 12
Second loop iteration
digit = 12 % 10 = 2; reversed = 1*10 + 2 = 12; num = 12 / 10 = 1
Third loop iteration
digit = 1 % 10 = 1; reversed = 12*10 + 1 = 121; num = 1 / 10 = 0
Compare original and reversed
original=121, reversed=121, they are equal, so palindrome
| num | digit | reversed |
|---|---|---|
| 121 | 1 | 1 |
| 12 | 2 | 12 |
| 1 | 1 | 121 |
Why This Works
Step 1: Extract digits from the number
Using num % 10 gets the last digit of the number to build the reversed number.
Step 2: Build the reversed number
Multiply reversed by 10 and add the digit to shift digits left and append the new digit.
Step 3: Compare original and reversed
If the reversed number equals the original, the number reads the same forwards and backwards, so it is a palindrome.
Alternative Approaches
package main import ( "fmt" "strconv" ) func main() { var num int fmt.Print("Enter a number: ") fmt.Scan(&num) s := strconv.Itoa(num) rev := "" for i := len(s) - 1; i >= 0; i-- { rev += string(s[i]) } if s == rev { fmt.Printf("%d is a palindrome number\n", num) } else { fmt.Printf("%d is not a palindrome number\n", num) } }
package main import "fmt" func reverse(num, rev int) int { if num == 0 { return rev } return reverse(num/10, rev*10+num%10) } func main() { var num int fmt.Print("Enter a number: ") fmt.Scan(&num) if num == reverse(num, 0) { fmt.Printf("%d is a palindrome number\n", num) } else { fmt.Printf("%d is not a palindrome number\n", num) } }
Complexity: O(d) time, O(1) space
Time Complexity
The loop runs once for each digit in the number, so time grows linearly with the number of digits, O(d).
Space Complexity
Only a few variables are used regardless of input size, so space complexity is constant, O(1).
Which Approach is Fastest?
The integer reversal method is fastest and uses least memory compared to string conversion or recursion.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Integer reversal | O(d) | O(1) | Performance and memory efficiency |
| String conversion | O(d) | O(d) | Simplicity and readability |
| Recursive reversal | O(d) | O(d) | Learning recursion concepts |