728x90
반응형

//String 변환
public class cote1 {
public static void main(String[] args) {
Test test = new Test();
int result = test.Solution(1234);
System.out.println("result : " + result);
}
}
class Test {
public int Solution(int n) {
int answer = 0;
String s = Integer.toString(n);
for(int i=0; i<s.length(); i++) {
answer += Integer.parseInt(s.substring(i, i+1));
}
return answer;
}
}
//나눗셈
public class Solution {
public int solution(int n) {
int answer = 0;
while(n > 0){
answer += n%10;
n/=10;
}
return answer;
}
}
//아스키코드 이용
public class Solution {
public int solution(int n) {
int answer = 0;
char[] arr = Integer.toString(n).toCharArray();
for(int i = 0; i < arr.length; i++){
answer += arr[i] - 48;
}
return answer;
}
}
0 부터 9 까지 아스키코드는 48 부터 57이다.
아스키코드 값인 48을 빼게 되면 그 차이만큼 반환하게 되는데
그 차이가 숫자와 같아서
arr[i] = '0' 또는 arr[i] = '48' 로 형변환을 리소스를 크게 사용하지 않고 사용 가능.
혼자 풀어보고 정답을 맞춘 후
다른 사람이 푼 풀이를 보면서 이렇게도 되네?
좋은 공부가 되는 것 같다.
728x90
반응형
'Algorithm > 프로그래머스' 카테고리의 다른 글
| [프로그래머스/Java]Comparator와 copyOfRange (0) | 2023.09.30 |
|---|---|
| [프로그래머스/Java] 정수 제곱근 판별 (0) | 2023.09.13 |
| [프로그래머스/Java] 문자열 내 p와 y의 개수 (0) | 2023.09.11 |
| [프로그래머스/Java] 자연수 뒤집어 배열로 만들기 (0) | 2023.09.07 |
| [프로그래머스/Java] 나머지가 1이 되는 수 찾기 (0) | 2023.09.06 |