Day 3: I4G 10 days of code challenge.

Day 3: I4G 10 days of code challenge.

Palindromes.

I remember that one time in February when everybody could not stop talking about palindromes.

I found out that 22/02/2022 could be written exactly in same order when reversed. Wednesday, 22nd February 2022 became a "palindrome" date, and suddenly, everyone said it was time to send out all our wishes to the universe because this date came only once in a century (or was it once in forever?).

Today's algorithm is about checking if a given number is a palindrome or not.

THOUGHT PROCESS

Of course, my first idea was to reverse the integer. Then check if this reversed value was the same as the initial integer. Only problem was that LeetCode suggested to solve the problem without converting to a string.

Why is this relevant? Reversing integers by first converting them to strings is relatively easy. (Strings? Strings are characters or words according to computers. So, an integer to a string is similar to 320 to "320". Yes, it just takes the addition of "" to convert something to a string)

However, It's a bit more tasking to reverse integers. Stay with me. I created a variable to store the reversed integer and stored a zero (0) there for now. Also, my integer is present as 342 for this example.

1.png

Next, I performed a mathematical operation on the integer (integer mod 10 = 2). Remember "mod" from math? (If you can't, please google it). The operation was used to get the last number in the integer and put it in the reversed as the first. How? By multiplying the reversed by 10 and adding the result from the equation (2).

2.png

Then, I removed the last number from the integer by dividing the integer by 10.

3.png

Then, I repeated the entire process until no number was left.

4.png

After all this, I checked if reversed = integer before pronouncing it a palindrome or not. In this case, 342 is not a palindrome.

Remember, negative numbers cannot be palindromes. So, to avoid that, I placed a rule that immediately returns false on contact with any number less than 0.

Time complexity: We divided the input by 10 for every iteration, so the time complexity is O(log10(n)) Space complexity: O(1)

Ciao!