Last active
May 25, 2020 14:54
-
-
Save DongguemYoo/94c59fe9e2fa03a16c1bbe17e573ea2a to your computer and use it in GitHub Desktop.
코딩테스트 연습 124나라의 숫자.cpp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//모르겠어서 구글링함 | |
진수표현에 대한 머리를 많이써보자 공부가 많이 필요함 | |
//포인트는 나눠서 나오는 몫으로 자리수를 만들수 있다는게 가장 중요한듯 일단 이해는 했음 | |
ex | |
13/3 ->4 ->value1 | |
4/3 ->1 ->value2+value1 | |
1/3 ->0 ->value3+value2+value1 | |
고로 13은 3자리 수로 표현이 될것이다 | |
이게 핵심인듯 | |
124라는 숫자는 3으로 나누어라는 힌트인듯하다 | |
번외 만약 7894 이런식이엿다면 어떻게 해야하는지도 풀어보자 | |
일단 풀이는 엄청 심플하다 | |
public string solution(int n) | |
{ | |
string answer = ""; | |
int rmd = 0; | |
while (n > 0) // 나눠질수있을때 까지 나눈다 | |
{ | |
rmd = n % 3; | |
n = n / 3; | |
if (rmd == 0) | |
{ | |
n -= 1; | |
rmd = 4; | |
} | |
answer = rmd + answer; | |
} | |
return answer; | |
} | |
//훨씬더 아름다운 풀이를 찾았다!! | |
#include <string> | |
#include <vector> | |
using namespace std; | |
string solution(int n) { | |
string answer = ""; | |
int rmd = 0; | |
while (n > 0) | |
{ | |
rmd = n % 3; | |
n = n / 3; | |
if (rmd == 0) | |
{ | |
n -= 1; | |
} | |
answer ="412"[rmd]+ answer; //"412"부분이 하이라이트이다 | |
//지렷다; | |
} | |
return answer; | |
} | |
번외 풀이 | |
public string solution(int n) | |
{ | |
string answer = ""; | |
int rmd = 0; | |
while (n > 0) | |
{ | |
rmd = n % 4; | |
n = n / 4; | |
if (rmd == 0) | |
{ | |
n -= 1; | |
} | |
answer = "7482"[rmd] + answer; //이렇게만 변경하면 적용된다;;미친거 아닌가...공부더하자... | |
} | |
return answer; | |
} | |
응용 2진수 만들기 (1제외) | |
public string solution(int n) | |
{ | |
string answer = ""; | |
int rmd = 0; | |
while (n > 0) | |
{ | |
rmd = n % 2; | |
n = n / 2; | |
if (rmd == 0) | |
{ | |
//n -= 1; | |
//원래 이게 있었는데 없앰 솔직히 -1 하는 이유를 모르겠음 | |
//어떻게 돌아가는지는 알겠는데 왜 이런식으로 생각할 수 있었는지를 모르겠음..ㅠㅠ | |
//대단하다... | |
뺀 이유는 모르겠지만 | |
3,2,1을 적용해보면 3일때 1을 빼지 않으면 공식이 성립하지 않는것은 알수있음 | |
} | |
answer = rmd + answer; | |
} | |
return answer; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment