给定数字N ,任务是首先检查给定的数字是否为二进制,并且其值应大于1。如果N为二进制表示,则为true;否则为false 。
例子:
Input: N = 1010
Output: true
Explanation:
Given number is greater than 1 and none of its digits is greater than 1. Thus, it is a binary number greater than 1.
Examples: N = 1234
Output: false
Explanation:
Given number is greater than 1 but some of its digits { 2, 3, 4} are greater than 1. Thus, it is not a binary number.
迭代方法:
- 检查该数字是否小于或等于1。如果是,则打印false。
- 否则,如果number大于1,则检查数字的每个数字是否为1或0 。
- 如果数字的任何数字大于1,则输出false ,否则输出true 。
下面是上述方法的实现:
Java
// Java program for the above approach
class GFG {
// Function to check if number
// is binary or not
public static boolean isBinaryNumber(int num)
{
// Return false if a number
// is either 0 or 1 or a
// negative number
if (num == 0 || num == 1
|| num < 0) {
return false;
}
// Get the rightmost digit of
// the number with the help
// of remainder '%' operator
// by dividing it with 10
while (num != 0) {
// If the digit is greater
// than 1 return false
if (num % 10 > 1) {
return false;
}
num = num / 10;
}
return true;
}
public static void main(String args[])
{
// Given Number N
int N = 1010;
// Function Call
System.out.println(isBinaryNumber(N));
}
}
Java
// Java program for the above approach
import java.util.regex.*;
class GFG {
// Function to check number is
// binary or not
public static boolean isBinaryNumber(int num)
{
// Regex to check a number
// is binary or not
String regex = "[01][01]+";
// Match the given number with
// the regular expression
return Integer
.toString(num)
.matches(regex);
}
// Driver Code
public static void main(String args[])
{
// Given Number
int N = 1010;
System.out.println(isBinaryNumber(N));
}
}
输出:
true
时间复杂度: O(K) ,K是N中的位数
辅助空间: O(1)
正则表达式方法:
- 将数字转换为字符串。
- 创建如下所述的正则表达式:
regex = “[01][01]+”;
在哪里:
- [01] [01]匹配以下{“ 00”,“ 01”,“ 10”,“ 11”)之一。
- +匹配前一个正则表达式的一个或多个出现
- 将给定数字与正则表达式匹配。如果匹配,则返回true,否则返回false。
下面是上述方法的实现:
Java
// Java program for the above approach
import java.util.regex.*;
class GFG {
// Function to check number is
// binary or not
public static boolean isBinaryNumber(int num)
{
// Regex to check a number
// is binary or not
String regex = "[01][01]+";
// Match the given number with
// the regular expression
return Integer
.toString(num)
.matches(regex);
}
// Driver Code
public static void main(String args[])
{
// Given Number
int N = 1010;
System.out.println(isBinaryNumber(N));
}
}
输出:
true
时间复杂度: O(K) ,K是N中的位数
辅助空间: O(1)