알고리즘/프로그래머스
[JAVA] 프로그래머스 Lv1. 문자열을 정수로 바꾸기 - 다른 풀이
수진보배
2020. 10. 21. 01:01
728x90
public class StrToInt {
public int getStrToInt(String str) {
boolean Sign = true;
int result = 0;
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i); // str의 한 글자 가져오기
if (ch == '-') // ch가 '-' 일 때
Sign = false;
else if(ch !='+') // ch가 '-' , '+' 가 아닐 때 즉, 숫자일때
result = result * 10 + (ch - '0');
// for문이 돌면서 자리에 맞게 10씩 곱해짐. ch는 문자이기 때문에 '0'을 빼서 숫자로 변환 시켜줌
}
return Sign?1:-1 * result; // sign이 true 일 때는 1, false 일 때는 -1을 result에 곱한다.
}
728x90