https://school.programmers.co.kr/learn/courses/30/lessons/120885
이진수를 의미하는 두 개의 문자열 bin1
과 bin2
가 매개변수로 주어질 때, 두 이진수의 합을 return하도록 solution 함수를 완성해주세요.
return 값은 이진수를 의미하는 문자열입니다.
1 ≤ bin1, bin2의 길이 ≤ 10
bin1과 bin2는 0과 1로만 이루어져 있습니다.
bin1과 bin2는 "0"을 제외하고 0으로 시작하지 않습니다.
bin1 | bin2 | result |
---|---|---|
"10" | "11" | "101" |
"1001" | "1111" | "11000" |
10 + 11 = 101 이므로 "101" 을 return합니다.
1001 + 1111 = 11000 이므로 "11000"을 return합니다.
import java.util.ArrayList;
class Solution {
public String solution(String bin1, String bin2) {
String answer = "";
int len=bin1.length();
ArrayList <Integer> intBin1=new ArrayList <Integer>();
ArrayList <Integer> intBin2=new ArrayList <Integer>();
for(int i=0;i<len;i++){
intBin1.add(Integer.valueOf(bin1.charAt(i)-'0'));
}
for(int i=0;i<bin2.length();i++){
intBin2.add(Integer.valueOf(bin2.charAt(i)-'0'));
}
if(len==bin2.length()){
for(int i=len-1;i>=0;i--){
if(intBin1.get(i)+intBin2.get(i)>=2){
intBin1.set(i,(intBin1.get(i)+intBin2.get(i))-2);
if(i==0){
intBin1.add(0,1);
}
else{
intBin1.set(i-1,intBin1.get(i-1)+1);
}
}
else{
intBin1.set(i,(intBin1.get(i)+intBin2.get(i)));
}
}
for(int i=0;i<intBin1.size();i++){
answer+=String.valueOf(intBin1.get(i));
}
}
else if(len>bin2.length()){ // "1011" "010"
int temp=bin2.length()-1;
for(int i=len-1;i>=0;i--){
if(temp>=0){
if(intBin1.get(i)+intBin2.get(temp)>=2){
intBin1.set(i,(intBin1.get(i)+intBin2.get(temp))-2);
if(i==0){
intBin1.add(0,1);
}
else{
intBin1.set(i-1,intBin1.get(i-1)+1);
}
}
else{
intBin1.set(i,(intBin1.get(i)+intBin2.get(temp)));
}
}
else{
if(intBin1.get(i)>=2){
intBin1.set(i,intBin1.get(i)-2);
if(i==0){
intBin1.add(0,1);
}
else{
intBin1.set(i-1,intBin1.get(i-1)+1);
}
}
}
temp--;
}
for(int i=0;i<intBin1.size();i++){
answer+=String.valueOf(intBin1.get(i));
}
}
else if(len<bin2.length()){
int temp=len-1;
for(int i=bin2.length()-1;i>=0;i--){
if(temp>=0){
if(intBin2.get(i)+intBin1.get(temp)>=2){
intBin2.set(i,(intBin2.get(i)+intBin1.get(temp))-2);
if(i==0){
intBin2.add(0,1);
}
else{
intBin2.set(i-1,intBin2.get(i-1)+1);
}
}
else{
intBin2.set(i,(intBin2.get(i)+intBin1.get(temp)));
}
}
else{
if(intBin2.get(i)>=2){
intBin2.set(i,intBin2.get(i)-2);
if(i==0){
intBin2.add(0,1);
}
else{
intBin2.set(i-1,intBin2.get(i-1)+1);
}
}
}
temp--;
}
for(int i=0;i<intBin2.size();i++){
answer+=String.valueOf(intBin2.get(i));
}
}
return answer;
}
}
사실은 문자열 2진수를 10진수로 바꾸고 계산을 한 다음 2진수로 다시 바꾸는 게 더 쉬웠을 것 같기도 하다.
둘의 길이가 같을 때만 생각했는데, 그게 아니고다를때도 생각해야했다.