알고리즘/백준풀이7. 수학
(8) [C++, Java] 백준 No.1212 : 8진수 2진수
Storage Gonie
2019. 5. 7. 13:27
반응형
문제
풀이
자세한 풀이 :
# C++(나의 풀이)
- 각 자리를 2진수로 변환해주는 것은 공통적으로 이뤄지는 것이므로 함수화 하였고,
두번째 자리부터는 함수의 결과에다가 앞에 0을 채워주었음.
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
string change8to2(char c)
{
string result = "";
int num = c - '0';
if(num == 0) // 이걸 해주지 않으면 0이 입력일 때 빈 문자열이 반환된다.
return "0";
while (num != 0)
{
result += to_string(num % 2);
num = num / 2;
}
reverse(result.begin(), result.end());
return result;
}
int main() {
string s;
cin >> s;
for(int i = 0; i < s.size(); i++)
{
if (i == 0)
cout << change8to2(s[i]);
else
{
string temp = change8to2(s[i]);
while(temp.size() != 3)
temp = '0' + temp;
cout << temp;
}
}
}
# C++(백준 풀이)
- 하드코딩 방식이라서 별로 따라하고 싶은방식이 아님
#include <cstdio>
#include <string>
#include <iostream>
using namespace std;
string eight[8] = {"000","001","010","011","100","101","110","111"};
int main(){
string s;
cin >> s;
bool start = true;
if (s.length() == 1 && s[0]-'0' == 0)
cout << "0";
for (int i=0; i<s.length(); i++)
{
int n = s[i]-'0';
if (start == true && n < 4)
{
if (n == 0)
continue;
else if(n == 1)
cout << "1";
else if (n == 2)
cout << "10";
else if (n == 3)
cout << "11";
start = false;
}
else
{
cout << eight[n];
start = false;
}
}
}
# Java
import java.util.*;
public class Main {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
String[] eight = {"000","001","010","011","100","101","110","111"};
String s = sc.nextLine();
boolean start = true;
if (s.length() == 1 && s.charAt(0) == '0') {
System.out.print(0);
}
for (int i=0; i<s.length(); i++) {
int n = s.charAt(i) - '0';
if (start == true && n < 4) {
if (n == 0) {
continue;
} else if (n == 1) {
System.out.print("1");
} else if (n == 2) {
System.out.print("10");
} else if (n == 3) {
System.out.print("11");
}
start = false;
} else {
System.out.print(eight[n]);
start = false;
}
}
System.out.println();
}
}
반응형