[英]I want to check if a number is binary or not in decimal numbers but it didnt work
我想检查一个数字是否为十进制数字,但它从数字 1 到 n 都不起作用。 例如,从 1 到 10,我们有 2 个十进制数,其中包含 0,1。我该如何更改它?
import java.util.Scanner;
public class Main
{
public static void main(String args[]) {
int r = 0, c = 0, num, b;
int count=0;
Scanner sl = new Scanner(System.in);
System.out.println("Enter a number");
num = sl.nextInt();
for (int i = 1; i <= num; i++) {
if ((i % 10 == 0) || (i % 10 == 1))
c++;
r++;
i = i / 10;
}
if (c == r)
count++;
else{
}
System.out.println(count);
}
}
我不是 Java 开发人员,所以也许我的回答不好。但是您可以使用您的数字作为 str 然后检查 str 是否仅由 0 和 1 构成
也许这会有所帮助:: 如何检查字符串中是否只有选定的字符?
祝你今天过得愉快
这是您如何以优雅的方式做到这一点......
// Function to check if number
// is binary or not
public static boolean isBinaryNumber(int num)
{
if(num == 1 || num == 0) return true
if (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;
}
在这里,将使用 2 个循环,一个用于范围,另一个用于检查它是否为二进制。
我们将使用 flag 和 break 来跳过不必要的迭代,而不是 c 和 r。
int count=0;
boolean flag = true;
for(int i=1;i<=num;i++)
{
for(int j=i;j>0;j=j/10)
{
// if remainder is not 0 and 1, then it means it's not binary
// so we set flag as false
// and using break to break out of the current(inner) loop, it's no longer needed to check remaining digits.
if (j%10 > 1)
{
flag = false;
break;
}
}
// if flag is true, that means it's binary and we increment count.
// if flag is flase, that means it's not binary
if(flag)
count++;
// here we reset flag back to true
flag = true
}
System.out.println(count);
您也可以按照@jchenaud 的建议进行操作。 将其转换为字符串并检查它是否只包含0
和1
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.