Contents

Binary addition (with.Java)

   May 23, 2024     1 min read

This is an article about the β€œBinary number addition (with.Java)” problem.

As I solve coding test problems, I look back on the problems I solved and look into different solution methods to learn more.

Let’s look at the problem first.

problem

When two strings bin1 and bin2, which represent binary numbers, are given as parameters, complete the solution function to return the sum of the two binary numbers.

Restrictions

  • The return value is a string meaning a binary number.
  • 1 ≀ bin1, length of bin2 ≀ 10
  • bin1 and bin2 consist of only 0 and 1.
  • bin1 and bin2 do not start with zeros except β€œ0”.

Input/Output Example

bin1bin2result
β€œ10β€β€œ11β€β€œ101”
β€œ1001β€β€œ1111β€β€œ11000”

My solution to the problem

class Solution {
 public String solution(String bin1, String bin2) {
 String answer = "";
 int binarySum = Integer.parseInt(bin1,2) + Integer.parseInt(bin2,2);

 answer = Integer.toBinaryString(binarySum);

 return answer;
 }
}

Solved review

This function takes two binary strings as input, converts them to decimal, and returns the summed result back as a binary string.

First, we initialize the answer variable to an empty string.

Using the Integer.parseInt() function, convert the two input binary strings (bin1 and bin2) to decimal numbers and then add them. This calculates the sum of two binary numbers as a decimal number.

To convert the binary sum back to a binary string, we use the Integer.toBinaryString() function. This function converts a decimal number to a binary string.

Assigns the converted binary string to the answer variable and returns it.