본문 바로가기
알고리즘/프로그래머스

[프로그래머스] 숨어있는 숫자의 덧셈 (1) (JAVA/ 자바)

by pandastic 2025. 8. 9.
반응형

 

 

내가 푼 코드

class Solution {
    public int solution(String my_string) {
        int answer = 0;
        
        for(int i=0; i<my_string.length(); i++){
            if(my_string.charAt(i) > 48 && my_string.charAt(i) < 58){
                answer += (my_string.charAt(i) - 48);
            }
        }
        return answer;
    }
}

ASCII 코드를 사용하여 풀이하였다.

 

https://www.ascii-code.com/

 

ASCII table - Table of ASCII codes, characters and symbols

A complete list of all ASCII codes, characters, symbols and signs included in the 7-bit ASCII table and the extended ASCII table according to the Windows-1252 character set, which is a superset of ISO 8859-1 in terms of printable characters.

www.ascii-code.com

문자로 된 0 ~ 9 의 경우 10진수로 48 ~ 57이다.

10진수 문자
48 0
49 1
50 2
51 3
52 4
53 5
54 6
55 7
56 8
57 9

 

if(my_string.charAt(i) > 48 && my_string.charAt(i) < 58)

로 문자열의 각 자리가 1 ~ 9 사이에 있을 경우를 체크한다.

 

answer += (my_string.charAt(i) - 48);

문자 0의 10진수 값인 48을 빼주면 int로 변환이 되므로 빼서 answer에 더해주면 된다.

 

 

 

[ ASCII 코드 표 참고 ]

https://sheepone.tistory.com/47

 

ASCII Table 아스키 코드표

아스키 코드표  code 0 ~ 31ASCII control characters는 인쇄가 불가능한 제어코드들입니다.프린터 같은 주변기기들을 제어할 때 사용됩니다.0(0x00) NUL: 널 문자10(0x0A) LF: 개행(Line Feed), 줄바꿈13(0x0D) CR:

sheepone.tistory.com

 

반응형