728x90
안녕하세요.
오늘도 풀었습니다.
1281. Subtract the Product and Sum of Digits of an Integer
정말 많이 많이 쉬웠습니다.
문자열로 변환해서 하나씩 처리해도 되고,
public int subtractProductAndSum(int n) {
int product = 1;
int sum = 0;
String str = String.valueOf(n);
for (int i=0; i<str.length(); i++) {
int num = Integer.parseInt(str.charAt(i) + "");
product *= num;
sum += num;
}
return product - sum;
}
나머지 연산(%)를 사용해도 됩니다.
public int subtractProductAndSum(int n) {
int sum = 0, product = 1;
while (n > 0) {
sum += n % 10;
product *= n % 10;
n /= 10;
}
return product - sum;
}
너무 날먹한 것 같아서 한 문제 더 풀어야겠습니다..
728x90
'츄Log > 알고리즘 연습장' 카테고리의 다른 글
연습#14 (0) | 2023.12.13 |
---|---|
연습#13 (0) | 2023.12.12 |
연습#11 Check if the sentence Is Pangram (1) | 2023.12.11 |
연습#10 Consecutive Characters (0) | 2023.12.10 |
연습#9 Long Pressed Name (1) | 2023.12.10 |