Binary addition (with.Java)
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
bin1 | bin2 | result |
---|---|---|
β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.