2단계7 [프로그래머스][C++][2단계] 다음 큰 숫자 #include #include using namespace std; int solution(int n) { // 1. n을 2진수로 변환했을 때의 1의 갯수 구하기 // 2. n+1부터 1씩 증가시켜가면서 2진수로 변환했을 때의 1의 갯수 구하기 // 3. n과 1의 갯수 비교후 같으면 해당 수를 리턴 int nCount = 0; while(true) { int count = 0; // 현재 수를 이진수로 바꿨을 때 맨 뒷자리 수부터 1인지 확인 for(int i = 0; (n>>i) > 0; i++) { // 시프트 연산을 이용해 나온 수가 홀수인지 판단하여 마지막 자리의 수를 확인할 수 있음. if(((n>>i) % 2) == 1) count++; } if(nCount == 0) nCount = c.. 2023. 11. 9. [프로그래머스][C++][2단계] 숫자의 표현 #include #include using namespace std; int solution(int n) { int answer = 1; // 자기자신은 세고 들어감 if(n != 1 && n % 2 != 0) answer++; for(int i = 3; i 2023. 11. 7. [프로그래머스][C++][2단계] 이진 변환 반복하기 #include #include using namespace std; vector solution(string s) { vector answer; int num = 0; // 반복 횟수 int count = 0; // 제거된 0의 갯수 while(s != "1") { num++; // 모든 0 제거 string x; for(int i = 0; i 0) { bin += ((c % 2) + '0'); // 역순으로 저장됨 c /= 2; } // 역순 -> .. 2023. 11. 3. [프로그래머스][C++][2단계] 올바른 괄호 #include #include using namespace std; bool solution(string s) { bool answer = true; int count = 0; for(int i = 0; i 0) answer = false; return answer; } 1. '('와 ')'의 갯수를 세서 같은 경우에만 올바른 것이므로 해당 경우를 찾아야한다. 2. 먼저 갯수를 셀 count 변수를 선언하고, 문자열 s를 반복하여 각 문자들을 탐색한다. 3. 문자가 '(' 인 경우는 count를 증.. 2023. 11. 1. [프로그래머스][C++] 최솟값 만들기 #include #include #include using namespace std; int solution(vector A, vector B) { int answer = 0; sort(A.begin(), A.end()); sort(B.rbegin(), B.rend()); for(int i = 0; i < A.size(); i++) { answer += A[i] * B[i]; } return answer; } 1. 두 배열의 원소들을 각각 곱해서 더한 값이 최소가 나오려면, 한 쪽의 가장 작은 값과 다른 한 쪽의 가장 큰 값을 곱하고, 그 다음 작은 값과, 다른 한 쪽의 그 다음 큰 값을 곱하고 이렇게 한 쪽은 작은 값부터 오름차순으로 다른 한 쪽은 큰 값부터 내림차순으로 쌍을 지어 곱해주어야 한다. 2.. 2023. 10. 31. [프로그래머스][C++] JadenCase 문자열 만들기 #include #include using namespace std; string solution(string s) { for(int i = 0; i = 'a' && s[i] 대문자로 변경 s[i] = s[i] - 'a' + 'A'; continue; } if((s[i] == ' ') && (s[i + 1] >= 'a' && s[i + 1] 대문자로 변경 s[i+1] = s[i+1] - 'a' + 'A'; continue; } if(i != 0 && s[i - 1] != ' ' && s[i] >= 'A' && s[i] 소문자로 변경 s[i] = s[i] - 'A' + 'a'; } } return s; } 1. 입력받은 문자열 s의 각 .. 2023. 10. 31. [프로그래머스][C++] 최댓값과 최솟값 #include #include #include using namespace std; string solution(string s) { string answer = ""; vector nums; for(int i = 0; i < s.size(); i++) { int addNum = 0; bool isMinus = false; while(s[i] != ' ' && i < s.size()) { int curNum = s[i] - '0'; // 음수인 경우 if(s[i] == '-') { isMinus = true; i++; continue; } addNum = addNum * 10 + curNum; i++; } if(isMinus) addNum *= -1; nums.push_back(addNum); } so.. 2023. 10. 30. 이전 1 다음