[JAVA] 프로그래머스 자릿수 더하기

[JAVA] 프로그래머스 자릿수 더하기

728x90

알고리즘

JAVA 프로그래머스 자릿수 더하기

자릿수 더하기

1. 문제

https://programmers.co.kr/learn/courses/30/lessons/12931

2. 풀이

Interger.parseInt() : 괄호안 String을 int로 변환,

.substring(a, b) : a부터 b앞까지를 출력

어제 공부했던 함수들인데 막상 적용할려고 익숙하지 않아서인지 머리에서 바로바로 나오지 않는다....

import java.util.*; public class Solution { public int solution(int n) { // n을 문자로 바꾸기 String s = String.valueOf(n); int answer = 0; for(int i = 0; i < s.length(); i++){ // 다시 string을 int로 변환 answer += Integer.parseInt(s.substring(i, i+1)); } return answer; } }

[다른사람의 풀이]

while문을 통해 푼 풀이인데 숫자를 하나씩 뽑아낼 때 많이 쓰는 풀이법이다.

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

from http://yuricoding.tistory.com/53 by ccl(A) rewrite - 2021-11-10 17:27:48