This post is the first in a series of Golang-based answers to some code challenges on Leetcode. Please note that the solution I provided is not the only solution to this challenge, as there are other ways to solve this challenge. Please write down your alternative solutions and suggestions in the comments if you have one. I'll work on the Palindrome Number challenge in this post.
Given an integer
x
, returntrue
ifx
is a palindrome, andfalse
otherwise.
In this challenge, we are given an integer x
and tasked to determine whether the x
is a palindrome or not.
A palindrome is a word, number, phrase, or other sequence of symbols that reads the same backwards as forwards, such as madam or racecar, the date and time 12/21/33 12:21, and the sentence: "A man, a plan, a canal – Panama".
-- Wikipedia
That is, to say that if we have x = 121
, then it is a Palindrome, while x = 1234
isn't. Now, One way to solve the challenge is to do these steps:
- Check whether the
x
is a negative number or not, if so, return false. - Convert the
x
tostring
- Using the two pointers technique, traverse through
x
to compare the elements from left and right, and if they don't equal, then return false. Otherwise, return true.
Code:
func IsPalindrome(x int) bool {
if x < 0 {
return false
}
strX := strconv.Itoa(x)
j := len(strX) - 1
for i := 0; i < j; i++ {
if strX[i] != strX[j] {
return false
}
j--
}
return true
}
Explanation:
if x < 0 {
return false
}
Here we implement the first step with this code to determine whether x
is a negative number or not. Doing this will make the function early return and doesn't have to run unnecessary steps after.
strX := strconv.Itoa(x)
Next, change the x
from type int
to string
, and store it to a new variable strX
because we are gonna loop through it's elements. To do this, we can use one of Golang's strconv
functions, strconv.Itoa()
.
j := len(strX) - 1
for i := 0; i < j; i++ {
if strX[i] != strX[j] {
return false
}
j--
}
return true
After that, using the two pointers technique, we traverse the strX
, with i
starting from the first element and j
starting from the last element.
The i
will increment through the loop, while j
will decrement. Inside the loop we check if they are equal or not, when there is a single occurrence where they aren't equal, then return a false. Otherwise, return true.
That's all! You can check the code on my GitHub as well as solutions for other challenges here.
Top comments (0)