给定整数N ,任务是在给定数字的二进制表示中找到尾随零的数量。
例子:
Input: N = 12
Output: 2
Explanation:
The binary representation of the number 13 is “1100”.
Therefore, there are two trailing zeros in the 12.
Input: N = -56
Output: 3
Explanation:
The binary representation of the number -56 is “001000”.
Therefore, there are 3 trailing zeros present in -56.
方法:按照步骤解决问题
- 我们的想法是使用观察,在计算N个XOR用N后– 1,N的所有设置位左到最右边的设置位,即LSB设置位消失和N的最右边一组位为N的最左侧设置位^(N – 1) 。
- 打印减1的数字(N ^(N – 1))的位数。
下面是上述方法的实现:
C++
// C++ implementation
// of the above approach
#include
using namespace std;
// Function to print count of
// trailing zeroes present in
// binary representation of N
int countTrailingZeroes(int N)
{
// Count set bits in (N ^ (N - 1))
int res = log2(N ^ (N - 1));
// If res < 0, return 0
return res >= 0 ? res : 0;
}
// Driver Code
int main()
{
int N = 12;
// Function call to print the count
// of trailing zeroes in the binary
// representation of N
cout << countTrailingZeroes(N);
return 0;
}
Java
// Java implementation
// of the above approach
import java.io.*;
class GFG {
// Function to print count of
// trailing zeroes present in
// binary representation of N
public static int countTrailingZeroes(int N)
{
// Stores XOR of N and (N-1)
int res = N ^ (N - 1);
// Return count of set bits in res
return (int)(Math.log(temp)
/ Math.log(2));
}
// Driver Code
public static void main(String[] args)
{
int N = 12;
// Fucntion call to print the count
// of trailing zeroes in the binary
// representation of N
System.out.println(
countTrailingZeroes(N));
}
}
Python3
# Python3 implementation
# of the above approach
from math import log2
# Function to prcount of
# trailing zeroes present in
# binary representation of N
def countTrailingZeroes(N):
# Count set bits in (N ^ (N - 1))
res = int(log2(N ^ (N - 1)))
# If res < 0, return 0
return res if res >= 0 else 0
# Driver Code
if __name__ == '__main__':
N = 12
# Function call to prthe count
# of trailing zeroes in the binary
# representation of N
print (countTrailingZeroes(N))
# This code is contributed by mohit kumar 29.
C#
// C# implementation
// of the above approach
using System;
public class GFG{
// Function to print count of
// trailing zeroes present in
// binary representation of N
public static int countTrailingZeroes(int N)
{
// Stores XOR of N and (N-1)
int res = (int)Math.Log(N ^ (N - 1), 2.0);
// Return count of set bits in res
if(res >= 0)
return res;
else
return 0;
}
// Driver Code
static public void Main ()
{
int N = 12;
// Fucntion call to print the count
// of trailing zeroes in the binary
// representation of N
Console.WriteLine(
countTrailingZeroes(N));
}
}
// This code is contributed by Dharanendra L V.
输出:
2
时间复杂度: O(log(N))
辅助空间: O(1)