Binary Palindromic Numbers RRS feed

All replies

  • We do not provide answers to homework/test questions.

    Michael Taylor http://www.michaeltaylorp3.net

    Wednesday, January 22, 2020 2:40 PM
  • We cannot write the code for you, but we can give you some hints as to how to accomplish the result.

    I have the following idea:

    To make the number a palindrome, you need to make the rightmost bit match the leftmost bit, the second bit on the right match the second on the left... repeat for the third, fourth, etc., until you reach the center of the binary number. You wish to change the bits on the right and not those on the left, since the former will require a smaller number of increments or decrements. The number of increments or decrements is 1 for bit 0, 3 for bit 1, 7 for bit 2, etc., i.e., 2^N-1. This gives you a quick way to calculate the number of increments or decrements needed to make the number a palindrome.

    However, I think that coding this in 20 minutes (as you are required) is a bit optimistic. Unless you are extremely proficient at writing code and manipulating binary numbers, coding this correctly and accounting for all possibilities, and testing it properly, is likely to require significantly more time.

    Wednesday, January 22, 2020 5:01 PM
  • > I think that coding this in 20 minutes is a bit optimistic.

    You think so?  For the range of values given above, a brute-force solution would be perfectly fine.  The maximum number is 2E9, which is 31 bits.  The goal will be to make the bottom bits look like the top bits, so you'd have at most 2^16 numbers to check for each test..  That's easy.

    Tim Roberts | Driver MVP Emeritus | Providenza & Boekelheide, Inc.

    Thursday, January 23, 2020 8:11 AM