Last Updated 2023 March 02
Happy 3/2/23 (m/d/yyyy, palindrome) or 2/3/23 (d/m/yyyy, repeating digits).
Because I don’t like to talk about myself much, I had trouble coming up with what to write for blogs. That is until I noticed people write blogs about solving Leetcode problems.
Weeks ago, I was outside and away from my desktop. There was an intermission of not doing anything. So I thought I could add to my collection of leetcode solutions even if the problem was easy.
The page for problems on leetcode wouldn’t load correctly on my phone, so I searched for a scraper. I didn’t run the scraper myself because the requirements seemed high. But the scraper did have a sample page of problems in simple HTML. This challenge was on there.
Given an integer x, return true if x is a palindrome, and false otherwise.
Follow up: Could you solve it without converting the integer to a string?
I can see how solutions like
return (str(x) == (str(x))[::-1])
(python) defeat the
purpose of the chalenge. For the original solution, I put the digits
of the number into a container.1 I technically did
not convert it to a string as a part of the solution, But I later
decided to revisit the problem and write a solution with no arrays
or containers.
There is a small story behind the check for
x < 100
instead of sigs = 2
. When I
didn’t use float'floor()
before converting to an
integer, numbers greater than 44 were treated as though they had
three digits. Turns out, integer()
will round up or
round down decimal values (integer(0.5)
= 1) which was a
slight curveball coming from languages that round down in all cases
for float-to-integer conversions.
function is_palindrome_no_array
(x : in integer)
return boolean is
: boolean := false;
result : integer; -- significant digits
sigs: integer; -- more significant digit
msd : integer; -- less significant digit
lsd : integer;
a begin
if x < 0 then
return false;
end if;
if x < 10 then
return true;
end if;
if x < 100 then
return (x mod 11 = 0);
end if;
:= integer(float'floor(math.log(float(x), 10.0))) + 1;
sigs for i in 0..(sigs/2) loop
:= (x/(10 ** i)) rem 10;
lsd := (x/(10 ** (sigs-(i+1))));
a := a rem 10;
msd if msd /= lsd then
return false;
end if;
end loop;
return true;
end;
function is_palindrome
(x : in integer) return boolean is
: vector;
v : integer := x;
operand : integer := 1;
i begin
if x < 0 then
return false;
end if;
if x < 10 then
return true;
end if;
while operand > 0 loop
.append(operand rem 10);
v:= (operand/10);
operand end loop;
(v);
print--put_line(integer'image(v.element(0)));
--put_line(integer'image(v.last_index));
if v.first_element /= v.last_element then
return false;
end if;
while i < ((v.last_index)/2) loop
if v.element(v.first_index + i)
/= v.element(v.last_index - i) then
return false;
end if;
:= i + 1;
i end loop;
return true;
end;