티스토리 뷰
https://school.programmers.co.kr/learn/courses/30/lessons/12931?language=java
프로그래머스
SW개발자를 위한 평가, 교육, 채용까지 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프
programmers.co.kr
문제 설명
내가 푼 방식
- int를 String으로 형변환 후 toCharArray() 메서드를 활용하여 char[] 배열에 담기
- 반복문(for)을 통해 answer에 값 더해주기
- char 타입의 문자 '1'을 int 타입의 숫자 1로 변환하려면 ASCII값을 이용하여 변환하기
- '1'의 ASCII 값은 49이고, '0'의 ASCII 값은 48입니다. 따라서 '1'-'0'은 1이 입니다.
- '0' ~ '9'까지의 숫자 문자에 대해 적용 가능합니다.
내가 푼 코드
import java.util.*;
public class Solution {
public int solution(int n) {
int answer = 0;
char[] temp = Integer.toString(n).toCharArray();
for(char a : temp) {
answer += a -'0';
}
return answer;
}
}
아래 다른 사람이 푼 코드
- 형변환 없이 정수 연산을 사용하여 자릿수를 구하는 방식
- n%10으로 마지막 자릿수를 추출하여 answer에 더하고, n /= 10으로 마지막 자릿수를 제거
- n이 0이 될 때까지 반복
import java.util.*;
public class Solution {
public int solution(int n) {
int answer = 0;
while (n != 0) {
answer += n % 10;
n /= 10;
}
return answer;
}
}
이렇게도 풀 수 있는데 왜 문제를 읽으면서 형변환으로 풀어야지 하는 생각이 먼저 들었을까..?
끝.
728x90
'Java' 카테고리의 다른 글
[Algorithms] 최대공약수, 최소공배수 with 프로그래머스 (0) | 2024.11.19 |
---|---|
[프로그래머스] 휴대폰 번호 가리기 - Java (0) | 2024.11.11 |
[Algorithms] 삽입 정렬 (0) | 2024.10.07 |
[Algorithms] 선택 정렬 (0) | 2024.09.30 |
[Algorithms] 버블 정렬 (0) | 2024.08.31 |
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- bool
- Lambda
- combinations
- permutations
- isdigit
- Method
- isalpha
- Built-in Functions
- Upper
- zip
- function
- index
- for
- Lower
- Python
- operators
- If
- find
- counter
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
글 보관함