Monday, February 17, 2020

1342. Number of Steps to Reduce a Number to Zero (Easy)

Q
Given a non-negative integer num, return the number of steps to reduce it to zero. If the current number is even, you have to divide it by 2, otherwise, you have to subtract 1 from it.

Example 1:
Input: num = 14
Output: 6
Explanation: 
Step 1) 14 is even; divide by 2 and obtain 7. 
Step 2) 7 is odd; subtract 1 and obtain 6.
Step 3) 6 is even; divide by 2 and obtain 3. 
Step 4) 3 is odd; subtract 1 and obtain 2. 
Step 5) 2 is even; divide by 2 and obtain 1. 
Step 6) 1 is odd; subtract 1 and obtain 0.
Example 2:
Input: num = 8
Output: 4
Explanation: 
Step 1) 8 is even; divide by 2 and obtain 4. 
Step 2) 4 is even; divide by 2 and obtain 2. 
Step 3) 2 is even; divide by 2 and obtain 1. 
Step 4) 1 is odd; subtract 1 and obtain 0.
Example 3:
Input: num = 123
Output: 12

Constraints:
  • 0 <= num <= 10^6

A:

if( (num & 1) ==0)
和 if (num &1 ==0)
结果是不一样的。操,我是个SB
--------直接计算---------------------


class Solution {
public:
    int numberOfSteps (int num) {
        int res = 0;
        while(num > 0)
        {
            if( (num & 1) ==0)
            {
                num = num>>1;
            }else
            {
                num = num-1;
            }
            res ++;
        }
        return res;
    }
};



*****************计算1 的数量,和最高的 1 的位数*****************




1 comment:

  1. In this fashion my colleague Wesley Virgin's biography launches in this SHOCKING AND CONTROVERSIAL VIDEO.

    You see, Wesley was in the military-and shortly after leaving-he found hidden, "SELF MIND CONTROL" tactics that the government and others used to get whatever they want.

    These are the EXACT same secrets many celebrities (especially those who "come out of nowhere") and the greatest business people used to become rich and successful.

    You probably know that you use only 10% of your brain.

    Really, that's because the majority of your brain's power is UNCONSCIOUS.

    Perhaps this expression has even taken place INSIDE OF YOUR very own head... as it did in my good friend Wesley Virgin's head 7 years back, while riding a non-registered, garbage bucket of a car with a suspended driver's license and with $3 in his bank account.

    "I'm so fed up with going through life paycheck to paycheck! When will I become successful?"

    You've taken part in those types of thoughts, am I right?

    Your very own success story is waiting to be written. Go and take a leap of faith in YOURSELF.

    Take Action Now!

    ReplyDelete