Converting decimals into binaries of only two digits: 1 and 2

Viewed 40

I have a problem with an exercise form my uni book. Here it is:

We are interested in a binary system representing positive integers with only two digits: 1 and 2 (no zeroes!). The subsequent positions correspond to the successive powers of the two, as in the usual binary notation: at the k-th position there is a digit whose value is multiplied by 2^k for k = 0, 1, 2... . In this system - as there are no leading zeros - in addition to formerly mentioned number representation, we use a value that specifies the number of selected digits, let's call it c. Each number is therefore represented by a pair (a, c), where a is a finite sequence of 1 and 2, and c determines the length of that sequence. For example, the pair (12, 3) represents the number 4, and the pair (221, 3) represents the number 13. Write a function which, for a positive number x, determines the representation of its value in the system in question and passes it through the parameter y. Let's agree that in case x is not positive, the value of field c should be 0.

I found that I can easly convert decimal input to binary system and then convert binary to the system mentioned in the exercise. Startng from right I need to remove zeros by converting higher digit 1 into lower digit 2.

E.g.: Decimal = 21. Binary = 10101. The system form the exercise = 10101 -> 10021 ; 10021 -> 02021 -> 01221

However, there is probably more efective solution that would convert decimal directly to the system from the exercise. I'd appreciate your help in finding the algorithmic path of thinking. I would then code it by myself to make sure I understand it.

It is my first post on the forum and english is not my native language. I am sorry if I did not express myself clear enough.

Kind regards

1 Answers

Let n be the number that we're trying to represent. The number c has to satisfy

20 + 21 + … + 2c−1 = 2c − 1 ≤ n ≤ 2c+1 - 2 = 2 (20 + 21 + … + 2c−1).

By inspection, these ranges partition the natural numbers, so the unique solution is c = ⌊log2 (n+1)⌋. The floor-log often can be computed with a single instruction, or you can use a bit-twiddling hack.

Once we know c, we just have to find the usual binary representation of n − (20 + 21 + … + 2c−1) = n − (2c − 1) and add one to each digit.

Related