이진수 더하기 / Lv.0
문제 설명 )
이진수를 의미하는 두 개의 문자열 bin1과 bin2가 매개변수로 주어질 때, 두 이진수의 합을 return하도록 solution 함수를 완성해주세요.
제한 사항 )
- return 값은 이진수를 의미하는 문자열입니다.
- 1 ≤ bin1, bin2의 길이 ≤ 10
- bin1과 bin2는 0과 1로만 이루어져 있습니다.
- bin1과 bin2는 "0"을 제외하고 0으로 시작하지 않습니다.
입출력 예 )
입출력 예 설명 )
입출력 예 #1
- 10 + 11 = 101 이므로 "101" 을 return합니다.
입출력 예 #2
- 1001 + 1111 = 11000 이므로 "11000"을 return합니다.
풀이)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
|
#include <string>
#include <vector>
#include <bitset>
using namespace std;
string to_binary(int number)
{
string temp = "";
// 0일 경우 예외처리
if (number == 0)
{
return "0";
}
// 이진수로 만들기
else {
while (number > 0)
{
if(number % 2)
{
temp = "1" + temp;
number /= 2;
}
else {
temp = "0" + temp;
number /= 2;
}
}
}
return temp;
}
string solution(string bin1, string bin2) {
string answer = "";
// 비트셋 이용
bitset<100> bs1(bin1);
bitset<100> bs2(bin2);
int number = bs1.to_ulong() + bs2.to_ulong();
answer = to_binary(number);
return answer;
}
|
cs |
출처 : https://school.programmers.co.kr/learn/courses/30/lessons/120885
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
'Develop > 프로그래머스 (Cpp)' 카테고리의 다른 글
[프로그래머스] 로그인 성공? (C++) (0) | 2023.03.03 |
---|---|
[프로그래머스] 치킨 쿠폰 (C++) (0) | 2023.03.03 |
[프로그래머스] A로 B 만들기 (C++) (0) | 2023.03.01 |
[프로그래머스] k의 개수 (C++) (0) | 2023.03.01 |
[프로그래머스] 중복된 문자 제거 (C++) (0) | 2023.03.01 |