jayati

Minimum Operations to Reduce an Integer to 0

Feb 19th, 2023
149
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.31 KB | None | 0 0
  1. class Solution {
  2. public:
  3.  
  4.     int minOperations(int n) {
  5.           int c=0, a, b;
  6.         while(n) {
  7.             c++;
  8.             a = pow(2, ceil(log(n)/log(2)));
  9.             b = pow(2, floor(log(n)/log(2)));
  10.             if(a-n < n-b) n = a-n;
  11.             else n = n-b;
  12.         }
  13.         return c;
  14.     }
  15. };
Advertisement
Add Comment
Please, Sign In to add comment