Optimized solution to calculate first powers of 2
I experienced many programming contests and olympiads but this one was really different. In a programming contest on Hacker Rank, I faced with a challenging problem and it was the main reason I failed the test. That question made me nervous and stressful so I gave up. When I found the solution after the test, I laughed so loud.
The question is:
Calculate sum of first powers of 2 without using any built-in language API to calculate the power. Implement optimized solution.
Well, there are two factors. First, not using built-in functions like
Math.pow and second implementing the optimized solution. So, of course a recursive function or for-loop is not the answer.
Use bitwise operations. How? Ok, let me show you a trick.
parseInt(10, '2') == Math.pow(2, 1); //2^1 = 2 parseInt(100, '2') == Math.pow(2, 2); //2^2 = 4 parseInt(1000, '2') == Math.pow(2, 3); //2^3 = 8 parseInt(10000,...
Continue reading →