코딩테스트/코드업
[코드업] (재귀함수) 2진수 변환 (C++)
Deff_a
2024. 4. 7. 13:52
(재귀함수) 2진수 변환
어떤 $10$진수 $n$이 주어지면 $2$진수로 변환해서 출력하시오. 예) 10 -----> 1010 0 -----> 0 1 -----> 1 2 -----> 10 1024 -----> 10000000000 이 문제는 반복문을 이용하여 풀 수 없습니
codeup.kr
문제
이 문제는 재귀 함수를 이용하여 10진수 정수인 n을 2진수로 변환해서 출력하는 문제이다.
풀이
n이 7이라 한다면
"1"+ to_string(3 % 2)+ to_string(7 % 2) => 111이 된다.
#include <iostream>
#include <string>
// https://codeup.kr/problem.php?id=1920&rid=0
using namespace std;
string binaryNumber(int num) {
if (num == 0) {
return "0";
}
else if (num == 1) {
return "1";
}
else {
return binaryNumber(num / 2) + to_string(num % 2);
}
}
int main() {
int num;
cin >> num;
cout << binaryNumber(num) << endl;
return 0;
}
CodingTestPractice/CodeUp/재귀 함수/(재귀함수) 2진수 변환.cpp at main · seungdo1234/CodingTestPractice
코딩 테스트 연습. Contribute to seungdo1234/CodingTestPractice development by creating an account on GitHub.
github.com