자릿수 더하기
2023. 1. 19. 01:22ㆍProgrammers/Java
문제
1) String으로 형 변환
1-1)
1
2
3
4
5
6
7
8
9
10
11
12
13
|
public class Solution {
public int solution(int n) {
String str = ""+n;
String[] strarr = str.split("");
int temp = 0;
for(String s : strarr){
temp += Integer.parseInt(s);
}
return temp;
}
}
|
cs |
1-2) valueOf()를 이용한 형 변환
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
import java.util.*;
import static java.lang.String.valueOf;
public class Solution {
public int solution(int n) {
String[] strarr = valueOf(n).split("");
int temp = 0;
for(String s : strarr){
temp += Integer.parseInt(s);
}
return temp;
}
}
|
cs |
valueOf()를 사용하면 인자를 String으로 바꿀 수 있다
2) 형 변환x
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
public class Solution {
public int solution(int n) {
int answer = 0;
while(n>0){
answer += n%10;
if(n < 10)
break;
n = n/10;
}
return answer;
}
}
|
cs |
'Programmers > Java' 카테고리의 다른 글
두 개 뽑아서 더하기 (0) | 2023.01.29 |
---|---|
문자열 내 p와 y의 개수 (0) | 2023.01.21 |
K번째수 (0) | 2023.01.19 |
숫자 문자열과 영단어 (0) | 2023.01.18 |
짝수와 홀수 (0) | 2023.01.17 |