2025.1.8.수

kinkin_a·2025년 1월 8일

내일배움캠프 TIL

목록 보기
36/100

문자열을 숫자로 바꿔주는 코드

Integer.parseInt(String s)

다른 분 풀이: 함수를 쓰지 않고 풀어 썼을때.

public class algorism {
    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');
                System.out.println(result);
            }
        }
        return Sign? result:-1 * result;
    }
    //아래는 테스트로 출력해 보기 위한 코드입니다.
    public static void main(String args[]) {
        algorism strToInt = new algorism();
        System.out.println(strToInt.getStrToInt("35789"));
    }```
    
    ```
코드를 입력하세요

4주차 과제 풀 때도 필요해서 좋았다.

0개의 댓글