Shortest possible sequence to get to a number

Viewed 2398

The first element of the sequence is 1.
i.e. A[0]=1 A[i+1] can either be 2A[i] or A[i]+1.

We have to find the shortest possible sequence.

e.g.:

If N is 18
 A[0]=1, A[1]=2,4,8,9,18

So my code was basically.

 int count = 0;
 for (int i = N, i != 1;){
 if (i % 2 == 0) { 
     i /= 2;
     ++count;
 } else{
     --i;
     ++count;
 }
 return count;

As you can see, this algorithm is pretty straightforward and will return the shortest length. However, the worst time complexity is O(N)

Is there any way to do it so that it is O(logN)?

1 Answers
Related