The number of operations for the algorithm to change the number to 0

Give you a non-negative integer num, please return the number of steps required to turn it into 0. If the current number is even, you need to divide it by 2; otherwise, subtract 1.

Example 1:

Input: num = 14

Output: 6

Explanation:

Step 1) 14 is an even number, divide by 2 to get 7.

Step 2) 7 is an odd number, subtract 1 to get 6.

Step 3) 6 is an even number, divide by 2 to get 3.

Step 4) 3 is an odd number, subtract 1 to get 2.

Step 5) 2 is an even number, divide by 2 to get 1.

Step 6) 1 is an odd number, subtract 1 to get 0.

Example 2:

Input: num = 8

Output: 4

Explanation:

Step 1) 8 is an even number, divide by 2 to get 4.

Step 2) 4 is an even number, divide by 2 to get 2.

Step 3) 2 is an even number, divide by 2 to get 1.

Step 4) 1 is an odd number, subtract 1 to get 0.

Algorithm 1: Direct implementation according to the steps of the question

int NumberOfSteps1(int* arr, int num)
{
    
    
	int i, count = 0;
	for (i = 0;i < num;i++) 
	{
    
    
		if (arr[i] % 2 != 0)//不能整除  次数+1
		{
    
    
			count += (arr[i] + 1) / 2;
		}
		else {
    
       //整除
			count += arr[i] / 2;
		}
	}
	return count;
}

Algorithm 2: All bitwise operators are used

int NumberOfSteps2(int num)  

{
    
      

     int count = 0;  

     while(num != 0)  

     {
    
      

         ++count;  

         //num&1用来判断奇偶;num&0xfffffffe奇数-1;num>>1除以2  

         num = (num&1)!=0 ? num&0xfffffffe : num>>1;  

     }  

    return count;  

} 

Guess you like

Origin blog.csdn.net/Gunanhuai/article/details/109146387