๐Ÿ—๏ธ Algorithm/โฌ› ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

โฌ› [Programmers] [Java] [Level1] ์ž๋ฆฟ์ˆ˜ ๋”ํ•˜๊ธฐ

Dbswnstjd 2023. 12. 11. 19:26

๋ฌธ์ œ

https://school.programmers.co.kr/learn/courses/30/lessons/12931?language=java

 

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

์ฝ”๋“œ ์ค‘์‹ฌ์˜ ๊ฐœ๋ฐœ์ž ์ฑ„์šฉ. ์Šคํƒ ๊ธฐ๋ฐ˜์˜ ํฌ์ง€์…˜ ๋งค์นญ. ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค์˜ ๊ฐœ๋ฐœ์ž ๋งž์ถคํ˜• ํ”„๋กœํ•„์„ ๋“ฑ๋กํ•˜๊ณ , ๋‚˜์™€ ๊ธฐ์ˆ  ๊ถํ•ฉ์ด ์ž˜ ๋งž๋Š” ๊ธฐ์—…๋“ค์„ ๋งค์นญ ๋ฐ›์œผ์„ธ์š”.

programmers.co.kr

ํ’€์ด

import java.util.*;

public class Solution {
    public int solution(int n) {
        int answer = 0;
        
        while(n > 0){
            answer += n%10;
            n/=10;
        }
        return answer;
    }
}

String์œผ๋กœ ๋ณ€ํ™˜ ํ›„ ๊ฐ๊ฐ์˜ ์ž๋ฆฌ์ˆ˜๋ฅผ ๋”ํ•ด๋„ ๋˜์ง€๋งŒ ๊ตณ์ด ๋ณ€ํ™˜ํ•˜์ง€ ์•Š๊ณ ๋„ ํ•ด๊ฒฐ ํ•  ์ˆ˜ ์žˆ๋Š” ๋ฌธ์ œ์ด๋‹ค.

n์„ 10์œผ๋กœ ๋‚˜๋ˆˆ ๊ฐ’์„ answer์— ๋”ํ•ด์ฃผ๊ณ  ๋” ์ด์ƒ ๋‚˜๋ˆ„์–ด ์ง€์ง€ ์•Š์„ ๋•Œ answer๋ฅผ returnํ•œ๋‹ค.