Programming/C++
c++ 10진법 진법 변환(string)
LordLoop
2021. 1. 17. 23:44
실무에서는 쓸 일이 없지만, 알고리즘 대회나 심심풀이 용으로 적합한 진법 변환.
기억 상기를 위해 예시 2개만 작성.
- 2진법
#include <vector>
#include <algorithm>
#include <string>
string BinarySystem(int num){
string make_base = "";
for(int i = num; i > 0; ){
make_base = to_string(i % 2) + make_base;
i /= 2;
}
return make_base;
}
int main(){
//생략
return 0;
}
- 3진법
#include <vector>
#include <algorithm>
#include <string>
string TernarySystem(int num){
string make_base = "";
for(int i = num; i > 0; ){
make_base = to_string(i % 3) + make_base;
i /= 3;
}
return make_base;
}
int main(){
//생략
return 0;
}
- 활용
#include <vector>
#include <algorithm>
#include <string>
int BinarySystem(int num){
string make_base = "";
for(int i = num; i > 0; ){
make_base = to_string(i % 2) + make_base;
i /= 2;
}
int base_intver = 0;
int ten_squared = 1;
for(int i = make_base.length() - 1; i >= 0; i--){
base_intver += make_base[i] * ten_squared;
ten_squared *= 10;
}
return base_intver;
}
int main(){
//생략
return 0;
}