[프로그래머스] 12931 자릿수 더하기
프로그래머스 level1
문제
문제 풀이
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Solution { | |
public int solution(int n) { | |
int sum = 0; | |
while (n != 0) { | |
sum += n % 10; | |
n = n / 10; | |
} | |
return sum; | |
} | |
} |
문제 리뷰
주어진 n의 각 자릿수의 합을 구하는 문제이다.
이 문제는 2가지만 알면 풀기 쉬운 문제이다.
- 일의 자릿수 자르기
n / 10
ex) 123 -> 12 -> 1
- 일의 자릿수 가져오기
n % 10
ex) 3 -> 2 -> 1
n이 0이 될 때까지 반복문을 실행하면 된다.
TMI
개운한 아침 ^o^
1일 2알고리즘 완료🤓
댓글남기기