I need to implement a function which decomposes a value into powers of two using java.
e.g: 14= 8 + 4 + 2
I need to find the powers of two which the value gets decomposed. For the above example I need 2,3,1 as outputs. How could I implement that?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
For this, you usually use bit-wise operations, namely the shift (<<,>>,>>>) and the bit-wise and (&) operator, because the internal representation of integers in computers already is binary, which is what you need.
In binary representation each integer value is a composition of powers of 2: 1, 2, 4, 8, 16, 32, …
So, 14 in decimal is in binary 1110: 8 + 4 + 2 + 0.
If you’re after some nice, generic algorithm, you may want to start decomposing decimal numbers into their powers of 10 and from there on extend your solution to other bases, like 2.