Message on Whatsapp 8879355057 for DSA(OA + Interview) + Fullstack Dev Training + 1-1 Personalized Mentoring to get 10+LPA Job
0 like 0 dislike
2,822 views
in Online Assessments by Expert (32,020 points) | 2,822 views

2 Answers

0 like 0 dislike

Solution
 

 

int minStep(long n) {
    int one = __builtin_popcountl(n);
    if (one <= 1) return one;
    return 1 + min(minStep(n+(n&(-n))), minStep(n-(n&(-n))));
}
by Expert (32,020 points)
0 like 0 dislike

Description
Given a positive integer n, return the minimum number of step to reduce n to 0.
In one step, you can add or subtract a power of two (2^i, i >= 0).

 

Example 1

 

Input: 14
Output: 2
Explanation: 14(01110) -> 16(10000) -> 0

 

Example 2

 

Input: 27
Output: 3
Explanation: 27(011011) -> 31(011111) -> 32(100000) -> 0

 

Example 3

 

Input: 1
Output: 1
by Expert (32,020 points)

Get best answers to any doubt/query/question related to programming , jobs, gate, internships and tech-companies. Feel free to ask a question and you will receive the best advice/suggestion related to anything you ask about software-engineering , development and programming problems .