Table of Contents
Palindrome Number
Problem Statement:
Given an integer x
, return true
if x
is a palindrome, and false
otherwise.
Golang code
package main
import "fmt"
func isPalindrome(x int) bool {
// Any negative input is not a palindrome
if x < 0 {
return false
}
number := x
reversedNumber := 0
for number > 0 {
lastDigit := number % 10
// Check for overflow before updating reversedNumber
// In Go, int is platform-dependent but commonly 32-bit or 64-bit.
// We can use math.MaxInt32 for 32-bit overflow checks if needed.
if reversedNumber > (1<<31-1-lastDigit)/10 { // Integer.MAX_VALUE in Go is 1<<31 - 1 for 32-bit
return false
}
reversedNumber = reversedNumber*10 + lastDigit
number /= 10
}
return reversedNumber == x
}
func main() {
fmt.Println(isPalindrome(121)) // true
fmt.Println(isPalindrome(-121)) // false
fmt.Println(isPalindrome(10)) // false
}
JAVA CODE
class Solution {
public boolean isPalindrome(int x) {
// any negative input is not a palindrome
if (x < 0) {
return false;
}
var number = x;
var reversedNumber = 0;
var lastDigit = 0;
while (number > 0) {
lastDigit = number % 10;
// check for overflow below updating reversedNumber
// In Java, int is a 32 bit signed integer
// from -2,147,483,648 to 2,147,483,647.
if (reversedNumber > Integer.MAX_VALUE - lastDigit){
return false;
}
reversedNumber = (reversedNumber * 10) + lastDigit;
number = number / 10;
}
if (reversedNumber == x){
return true;
}
return false;
}
}
Solve next problem #2
Similar Questions
- Palindrome Linked List
- Find Palindrome With Fixed Length
- Strictly Palindromic Number
- Count Symmetric Integers
Visit https: https://codeandalgo.com for more such contents
Leave a Reply