Skip to content
Advertisement

Addition of two given numbers

Basically is about the binary numbers, the user needs to input two random numbers, both numbers will be added, and the addition of those two numbers only needs to have ones and zeros for example 5+6==11 OR 55+55=110, then throw a message saying “the addition only has 1’s and 0’s, otherwise for example 25+46=71 or 575+575=1150 then a message saying the addition does not have only 1’s and 0’s.

I just started learning java and i can’t find anything helpful for this problem, i already know the conditionals if only have ones and zeros or not.

this is the code i already have, but when i input for example 575+575+1150 says only has 1’s and 0’s, i guess i cant use .contains for this.

public static void main(String[] args) {
    Scanner read = new Scanner(System.in);
    int n1;
    int n2;
    int add;
    
    System.out.print("Input Number 1: ");
    n1=read.nextInt();
    System.out.print("Input number 2: ");
    n2=read.nextInt();
    System.out.println();
    add=n1+n2;
    System.out.println("The addition is =  "+add); 
    
    String S = String.valueOf(add);
    
    if(S.contains("1") && S.contains("0")) {
     System.out.print("The addition only has 1's and 0's");
    }
    else{System.out.print("The addition does not only have 1's and 0's");}
        
}     

}

Advertisement

Answer

I saw your code and and the resultant sum 1150 does contain 1’s and 0’s.

s.contains(x); 

This function only checks if the string contains the value x or not. Since “1150” contains both 1’s and 0’s therefore your function prints the wrong output.

One way of solving this problem would be to add the two numbers and then check the resultant sum digit by digit. You can make a function that will do that for you.

public void checkOnesAndZeros(int resultantSum) {
        while (resultantSum > 0) {
            int remainder = resultantSum % 10;
            if(remainder != 1 && remainder != 0) {
                System.out.println("The addition does not have only 1’s and 0’s.");
                return;
            }
            resultantSum = resultantSum / 10;
        }
        System.out.println("The addition only has 1’s and 0’s");
    }
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement