본문 바로가기

Algorithm/Programers - C++

(121)
[프로그래머스]시저암호 문제 풀이 #include #include #include using namespace std; string solution(string s, int n) { string answer = ""; for(auto &a : s){ if(islower(a)){ a+=n%26; if(!islower(a)) a-=26; } else if(isupper(a)){ a+=n%26; if(!isupper(a)) a-=26; } } return s; } 만약 'z'인 상태에서 숫자 n을 더하게 되면, 그 문자는 더 이상 소문자가 아니게 되어버리기 때문에 islower을 사용해 소문자인지 아닌지 구별한 후, 아니라면(z 이상의 숫자가 되어버린다면) -26을 해 주어 z> a> b> c> d... 순서로 바뀌게끔 해주었다. ..
[프로그래머스] 문자열을 정수로 바꾸기 / stoi 문제 문자열 s를 숫자로 변환한 결과를 반환하는 함수, solution을 완성하세요. 풀이 1 #include #include using namespace std; int solution(string s) { int answer = 1; if(s[0] == '-'){ answer = -1; s = s.substr(1, s.length()-1); } answer *= stoi(s); return answer; } 풀이 2 #include #include using namespace std; int solution(string s) { int answer = stoi(s); return answer; } 사실 부호 처리를 따로 하지 않아도 stoi함수는 선행 공백 문자,+/-기호, 16 진수 접두사 (0x ..
[프로그래머스] 약수의 합 문제 정수 n을 입력받아 n의 약수를 모두 더한 값을 리턴하는 함수, solution을 완성해주세요. 풀이 #include #include #include using namespace std; int solution(int n) { int answer = 0; if(pow((int)sqrt(n),2) == n) answer+= (int)sqrt(n); for(int i=1; i
[프로그래머스]소수 찾기 / 에라토스테네스의 체 알고리즘 문제 1부터 입력받은 숫자 n 사이에 있는 소수의 개수를 반환하는 함수, solution을 만들어 보세요. 풀이 1 #include #include #include using namespace std; bool sosu(int n){ for(int i=2; i
[프로그래머스]수박수박수박수박수박수? 문제 풀이 #include #include using namespace std; string solution(int n) { string answer = ""; for(int i=0; i
[프로그래머스]문자열 다루기 기본/isdigit 문제 풀이 #include #include #include using namespace std; bool solution(string s) { if(s.length()==4 || s.length()==6){ for(int i=0; i
[프로그래머스]문자열 다루기 기본 / multiset, sort 문제 풀이 #include #include #include using namespace std; string solution(string s) { string answer = ""; multiset set; for(auto i : s) set.insert(i); for(auto i = set.rbegin(); i!= set.rend(); i++) answer += *i; // 역방향 반복자 return answer; } 해결방법 -multiset컨테이너를 사용해 중복을 허용하여 문자를 순서대로 정렬 -역방향 반복자로 컨테이너를 순회하며 answer에 문자 삽입 역방향 반복자 rbegin()은 마지막 원소를 가리키고, rend()는 첫 번째 원소의 하나 더 앞을 가리킨다. multiset - set과 같이..
[프로그래머스]문자열 내 p와 y의 개수 문제 풀이 #include #include #include using namespace std; bool solution(string s) { int answer = 0; for(int i=0; i