나의 풀이
class Solution {
public int solution(String s) {
int answer = Integer.parseInt(s);
return answer;
}
}
알고리즘이 아닌 함수를 사용했다.
다른 사람의 풀이
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);
if (ch == '-')
Sign = false;
else if(ch !='+')
result = result * 10 + (ch - '0');
}
return Sign?1:-1 * result;
}
//아래는 테스트로 출력해 보기 위한 코드입니다.
public static void main(String args[]) {
StrToInt strToInt = new StrToInt();
System.out.println(strToInt.getStrToInt("-1234"));
}
}
부호를 boolean 타입의 변수로 만드셨다.
for문을 통해 String 매개변수의 각 인덱스의 값을 결과 변수에 저장하셨다.
(ch - '0')는 문자를 숫자로 바꾸는 고전적인 방식이다.
예: '3' - '0' = 3
출처 : https://school.programmers.co.kr/learn/courses/30/lessons/12925/solution_groups?language=java
'CODING > CS, 알고리즘, 자료구조 공부' 카테고리의 다른 글
[프로그래머스] 정수 제곱근 판별 (0) | 2025.06.20 |
---|---|
[프로그래머스] 자연수 뒤집어 배열로 만들기 (1) | 2025.06.13 |
[프로그래머스] x만큼 간격이 있는 n개의 숫자 (1) | 2025.06.04 |
[프로그래머스] 나머지가 1이 되는 수 찾기 (0) | 2025.05.28 |
[프로그래머스] 약수의 합 (0) | 2025.05.27 |