如果在数字的二进制表示中未设置两个或更多连续位,则将数字称为稀疏数。编写函数以检查给定数字是否为稀疏。
例子 :
Input: x = 72
Output: true
Explanation: Binary representation of 72 is 01001000.
There are no two consecutive 1's in binary representation
Input: x = 12
Output: false
Explanation: Binary representation of 12 is 1100.
Third and fourth bits (from end) are set.
我们强烈建议您单击此处并进行实践,然后再继续解决方案。
如果我们仔细观察,那么我们会注意到,如果我们可以使用“给定数”的二进制表示形式的二进制“与”运算(即给定数的一半)(即给定数的一半)来判断该数是否稀疏。如果数字稀疏,则AND运算符的结果将为0;如果数字稀疏,则AND运算符的结果将为非零。
以下是上述想法的实现。
C++
// C++ program to check if n is sparse or not
#include
using namespace std;
// Return true if n is sparse, else false
bool checkSparse(int n)
{
// n is not sparse if there is set
// in AND of n and n/2
if (n & (n>>1))
return false;
return true;
}
// Driver program
int main()
{
cout << checkSparse(72) << endl;
cout << checkSparse(12) << endl;
cout << checkSparse(2) << endl;
cout << checkSparse(3) << endl;
return 0;
}
Java
// JAVA Code to Check if a
// given number is sparse or not
import java.util.*;
class GFG {
// Return true if n is
// sparse,else false
static int checkSparse(int n)
{
// n is not sparse if there
// is set in AND of n and n/2
if ((n & (n>>1)) >=1)
return 0;
return 1;
}
// Driver code
public static void main(String[] args)
{
System.out.println(checkSparse(72)) ;
System.out.println(checkSparse(12)) ;
System.out.println(checkSparse(2)) ;
System.out.println(checkSparse(3)) ;
}
}
//This code is contributed by Arnav Kr. Mandal.
Python3
# Python program to check
# if n is sparse or not
# Return true if n is
# sparse, else false
def checkSparse(n):
# n is not sparse if there is set
# in AND of n and n/2
if (n & (n>>1)):
return 0
return 1
# Driver code
print(checkSparse(72))
print(checkSparse(12))
print(checkSparse(2))
print(checkSparse(30))
# This code is contributed
# by Anant Agarwal.
C#
// C# Code to Check if a guven
// number is sparse or not
using System;
class GFG {
// Return true if n is
// sparse,else false
static int checkSparse(int n)
{
// n is not sparse if there
// is set in AND of n and n/2
if ((n & (n >> 1)) >= 1)
return 0;
return 1;
}
// Driver code
public static void Main()
{
Console.WriteLine(checkSparse(72));
Console.WriteLine(checkSparse(12));
Console.WriteLine(checkSparse(2));
Console.WriteLine(checkSparse(3));
}
}
// This code is contributed by Sam007.
PHP
> 1))
return 0;
return 1;
}
// Driver Code
echo checkSparse(72), "\n";
echo checkSparse(12), "\n";
echo checkSparse(2), "\n";
echo checkSparse(3), "\n";
// This code is contributed by Ajit.
?>
Javascript
输出 :
1
0
1
0