After performing a lot of experiments at the SEGP and EEDC Lab, you need a break. You see your roommate stuck on a math problem. He asks for your help and says he will give you a party at the NC if you solve this problem for him.
The problem is:
Initially you are given the number 0. After each day the numberdoubles itself. At any day, you can add the number 1 any number of times during the day.
You are given a number N and you need to tell the minimum number of times you have to add 1 to get N at any point of time.
Example:
Input: n = 4
Output: 1
Approach
C++
#include <bits/stdc++.h>using namespace std;long long helpRoomMate(long long n){long long cnt = 0;while (n > 0){if (n & 1){cnt++;n = n - 1;}elsen = n / 2;}return cnt;}int main(){long long n = 4;cout << helpRoomMate(n) << "\n";return 0;}
No comments:
Post a Comment