처음에 Integer.parseInt() 를 알고 있어서 쉬운데...?하면서 썼다가 다른 문제 풀이를 보면서 함수말고 다른 방법으로 써야된다는 것을 깨달았다. 나는 함수가 아니라 알고리즘 문제를 푸는 것이니까!!
for
, charAt()
if-else if-else
Integer.parseInt() 사용
class Solution {
public int solution(String s) {
int answer = Integer.parseInt(s);
return answer;
}
}
2번째 풀이
class Solution {
public int solution(String s) {
boolean Sign = true;
int result = 0;
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if (ch == '-')
Sign = false;
else if(ch !='+')
result = result * 10 + (ch - '0');
}
return Sign ? result : -1 * result;
}
}
ch-'0'
은 예를들어 s=1234일 때 첫번째 for문을 돌때 ch = '1'이다. '1'-'0'
은 유니코드로보면 49-48
로 숫자 1이 나온다.