Are the temp variable and casting needed in Problem 5.11 - IsPalindrome()?

#1

The book (1.4.8) and the code on GitHub use x_remaining and temp_x (respectively) for the LSD test. And modify x for MSD determinination.

Can we just use x itself for both MSD and LSD by iteratively dropping both from it in each iteration? (and reducing the msd_shift by a factor of 100 rather than 10)

I think the last division by 100 on a palindrome of an even n (the two middle digits remaining) would occur right before the loop conditional (i < (num_digits >> 1)) no longer holds true.

Could you also explain why the static_cast()'s are there. Won’t the “integer” doubles output by cmath’s floor() and pow() be stored correctly without the casting given the input/output range constraints? Maybe some compilers will complain about implicit demotion (mine doesn’t)?

25,26c25,26
<   int num_digits = static_cast<int>(floor(log10(x))) + 1;
<   int temp_x = x, msb_shift = static_cast<int>(pow(10, num_digits - 1));
---
>   int num_digits = floor(log10(x)) + 1;
>   int msb_shift = pow(10, num_digits - 1);
28c28
<     if (x / msb_shift != temp_x % 10) {
---
>     if (x / msb_shift != x % 10) {
32c32
<     msb_shift /= 10, temp_x /= 10;
---
>     msb_shift /= 100, x /= 10;
0 Likes

#2

Hey,

Thanks for your question. I think it is totally possible to use x itself for both MSD and LSD but extra cares need to be taken as you said.

The reason I use static_cast is for double to integer conversion which can be done implicitly but it is always a good practice to do this explicitly to eliminate compiler warnings which usually the smells of a bad code.

Please let us know if you have any problem.

0 Likes