JAVA - MATH - Binary Calculate

BASIC VERSION  (Length Limit)

 public class gfg {

 
    // Function to add two binary strings
    static String add_Binary(String x, String y)
    {
  
        int num1 = Integer.parseInt(x,2);
        //converting binary string into integer(decimal number)
       
        int num2 = Integer.parseInt(y,2);
        //converting binary string into integer(decimal number)
       
       
        int sum = num1 + num2;
        // Adding those two decimal numbers and storing in sum
         
        String result = Integer.toBinaryString(sum);
        //Converting that resultant decimal into binary string
 
        return result;
    }
 
    // The Driver code
    public static void main(String args[])
    {
        String x = "011011", y = "1010111";
 
        System.out.print(add_Binary(x, y));
    }
}


HARDCODE VERSION  (No Length Limit)

public class BinaryAdd {
public static void main(String[] args) {
String a = "111";
String b = "100";

StringBuilder res = new StringBuilder();
int i = a.length() - 1;//3 -1 = 2 //
int j = b.length() - 1;//3 -1 = 2
int carry = 0;
while(i >= 0 || j >= 0){
int sum = carry; //0 // 0
if(i >= 0) sum += a.charAt(i--) - '0'; //1 53-52 =1 -0 = 1 // sum = 1 // 1
if(j >= 0) sum += b.charAt(j--) - '0'; //1
carry = sum > 1 ? 1 : 0; //1 = 1 = carry = 0
res.append(sum % 2); // 110
}
if(carry != 0) res.append(carry);
System.out.println( res.reverse().toString());
}
}

留言

此網誌的熱門文章

MAP - Sort with stream

JAVA - DSF Example