[프로그래머스] 수 조작하기1

Seah Lee·2023년 6월 21일
0

프로그래머스

목록 보기
21/57

class Solution {
    public int solution(int n, String control) {

        for (int i=0;i<control.length();i++){
            
            char a = control.charAt(i);
            
            if (a=='w') n=n+1;
            else if (a=='s') n=n-1;
            else if (a=='d') n=n+10;
            else if (a=='a') n=n-10;
        }
        
        return n;
    }
}

.charAt 잘 써먹었다 !

[다른 사람의 풀이]

class Solution {
    public int solution(int n, String control) {
        int answer = n;

        for(char ch : control.toCharArray()) {
            switch(ch) {
                case 'w': answer += 1; break;
                case 's': answer -= 1; break;
                case 'd': answer += 10; break;
                case 'a': answer -= 10; break;
                default:break;
            }
        }

        return answer;
    }
}

switch case 문은 언제봐도 신기하며,, 저렇게 쓰는 for문 정의를 내가 잘 모르는 것 같아서
저것도 따로 공부해봐야겠다.

그 외, String[] 로 arr화 해서 split으로 나눈 뒤에 arr[i].equals 로 비교하는 사람

for(char c : control.toCharArray()){
            n += c == 'w' ? 1 : c == 's' ? -1 : c == 'd' ? 10 : -10;
        }

등이 있었다.

profile
성장하는 개발자

0개의 댓글