简体   繁体   中英

I want to check if a number is binary or not in decimal numbers but it didnt work

I want to check if a number if binary or not in decimal numbers but it didnt work from numbera 1 to n. for example from 1 to 10 we have 2 decimal numbers that contains 0,1.How can i change it?

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);
        }

    }

I am not a java dev so maybe my answer is not good.But you can use your number as str then check if the str is constituted only by 0 and 1

maybe this could help: : How to check if only chosen characters are in a string?

have a nice day

Here's how you can do it in an elegant way ...

 // 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;
    }

Here, will use 2 loops, one for range and one for checking if it's binary or not.
Instead of c and r, we will use flag and break in order to skip unnecessary iteration.

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);

You can also do as @jchenaud suggested. converting it to string and check if it only contains 0 and 1 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM