문제 설명
문자열 s를 숫자로 변환한 결과를 반환하는 함수, solution을 완성하세요.
제한 조건
입출력 예
예를들어 str이 "1234"이면 1234를 반환하고, "-1234"이면 -1234를 반환하면 됩니다.
str은 부호(+,-)와 숫자로만 구성되어 있고, 잘못된 값이 입력되는 경우는 없습니다.
쉬운 문제라고 하지만 실수가 잦아서 생각보다 조금 지연된 문제이다.
너무 초보자적인 실수지만 내가 초보자라... 다들 양해부탁드립니다 ㅎㅎ
먼저 길이를 제한해주자
if( 1 <= s.length && s.length <= 5)
여기서 내가 처음한 실수인데 .length는 함수이니깐 ()을 반드시 붙여줘야 한다.
if( 1 <= s.length() && s.length() <= 5 )
그리고 's' 라는 문자열이 숫자로만 이루어졌는지 확인하기 위해서
검색을 해보았는데 .charAt이라는 함수가 있다는 것을 알게 되었다.
charAt의 구현 방식은
public final class String {
// 문자열 데이터는 char 배열로 저장
private final char[] value;
// 문자열 길이
private final int count;
// charAt 메서드
public char charAt(int index) {
if (index < 0 || index >= count) {
throw new StringIndexOutOfBoundsException(index); // 유효하지 않은 인덱스 처리
}
return value[index]; // char 배열에서 인덱스 위치의 문자 반환
}
}
이런식으로 charAt이 작동한다.
마지막으로 문자열을 숫자열로 바꾸기 위해서 함수를 찾아보니
Integer.parseInt() 가 있었다.
이 메소드의 구현 방식은
public static int parseInt(String s) throws NumberFormatException {
return parseInt(s, 10); // 기본적으로 10진수 기반으로 처리
}
public static int parseInt(String s, int radix) throws NumberFormatException {
if (s == null) {
throw new NumberFormatException("null");
}
if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX) {
throw new NumberFormatException("Radix out of range");
}
int result = 0;
boolean negative = false;
int i = 0, len = s.length();
int limit = -Integer.MAX_VALUE;
int multmin;
int digit;
if (len > 0) {
char firstChar = s.charAt(0);
if (firstChar < '0') { // 음수 또는 '+' 기호 처리
if (firstChar == '-') {
negative = true;
limit = Integer.MIN_VALUE;
} else if (firstChar != '+') {
throw new NumberFormatException("For input string: \"" + s + "\"");
}
if (len == 1) { // "+" 또는 "-"만 있는 경우 예외 처리
throw new NumberFormatException("For input string: \"" + s + "\"");
}
i++;
}
multmin = limit / radix;
while (i < len) {
// 현재 문자 값을 숫자로 변환
digit = Character.digit(s.charAt(i++), radix);
if (digit < 0) {
throw new NumberFormatException("For input string: \"" + s + "\"");
}
if (result < multmin) {
throw new NumberFormatException("For input string: \"" + s + "\"");
}
result *= radix;
if (result < limit + digit) {
throw new NumberFormatException("For input string: \"" + s + "\"");
}
result -= digit;
}
} else {
throw new NumberFormatException("For input string: \"" + s + "\"");
}
return negative ? result : -result;
}
으로 많이 복잡하게 구성되어있다.
간단히 말로 정리하면
1. 입력 검증:
2. 부호 처리:
3. 문자 변환 및 계산:
4. 오버플로우 방지:
5. 최종 반환:
최종적으로 정리하자면
문자열 s를 숫자로 변환한 결과를 반환하는 함수, solution을 완성하세요.
에 대한 코드는
class Solution {
public int solution(String s) {
int answer = 0;
if( 1 <= s.length() && s.length() <= 5 && s.charAt(0) != 0){
answer = Integer.parseInt(s);
}
return answer;
}
}
이거다.
다른 사람의 풀이 중 좋아요 수가 가장 많은 것을 보니
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;
}
직접 이렇게 코딩할 수 있다는게 정말 대단한 것 같다.
[Java] 서울에서 김서방 찾기 (1) | 2025.01.20 |
---|---|
[Java] 두 정수 사이의 합 (3) | 2025.01.16 |
[Java] 자리수의 합으로 하샤드 수 판별하기 (2) | 2025.01.15 |
[Java] 정수 내림차순으로 배치하기 (1) | 2025.01.14 |
[Java] 정수 제곱근 판별 (0) | 2025.01.13 |