반응형


내가 푼 코드
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 코드를 사용하여 풀이하였다.
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
반응형
'알고리즘 > 프로그래머스' 카테고리의 다른 글
| [프로그래머스] 유한소수 판별하기 (JAVA/ 자바) (0) | 2025.12.08 |
|---|---|
| [프로그래머스] k의 개수 (JAVA/ 자바) (0) | 2025.08.26 |
| [프로그래머스] 피자 나눠 먹기 (JAVA/ 자바) (7) | 2025.08.06 |
| [프로그래머스] 홀수 vs 짝수 (JAVA/ 자바) (2) | 2025.08.02 |
| [프로그래머스] A 강조하기 (JAVA/ 자바) (5) | 2025.07.26 |