Post

[Programmers] #120893 - 대문자와 소문자 [Java][C++][Python]

[Programmers] #120893 - 대문자와 소문자 [Java][C++][Python]

문제 링크


1. 아이디어

대문자는 소문자로, 소문자는 대문자로 바꾸는 문제다. 영문자만 들어 있어 각 문자를 독립적으로 보고 대소문자만 뒤집으면 된다.


2. 코드

풀이 [Java][C++][Python]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
    public String solution(String my_string) {
        StringBuilder sb = new StringBuilder();
        for (char c : my_string.toCharArray()) {
            if (Character.isLowerCase(c)) {
                sb.append(Character.toUpperCase(c));
            } else {
                sb.append(Character.toLowerCase(c));
            }
        }

        return sb.toString();
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <bits/stdc++.h>
using namespace std;

string solution(string my_string) {
    string s;
    for (char c : my_string) {
        if (islower(c)) {
            s += toupper(c);
        } else {
            s += tolower(c);
        }
    }

    return s;
}

std::toupper는 int를 반환하지만 std::string에 +=로 붙이면 char로 변환돼 문자로 덧붙는다.

1
2
def solution(my_string):
    return my_string.swapcase()

swapcase로 대소문자를 한 번에 뒤바꿨다.


This post is licensed under CC BY 4.0 by the author.