본문 바로가기
코딩테스트/프로그래머스

[프로그래머스/Java] LV.1 자릿수 더하기

by ⓞㅖ롱 2022. 9. 13.

역시 간단한 문제다~

나같은 경우에는 int를 string으로 옮기고 string에서 char[] 문자배열로 옮기자! 라는 생각을 먼저 했다

 

내 코드

import java.util.*;

public class Solution {
    public int solution(int n) {
        int answer = 0;
        //int to string
        String str = Integer.toString(n);
        //string to char[]
        char[] arr = str.toCharArray();

        for(int i=0; i<arr.length; i++){
        	//배열의 문자 숫자로 변환하고 한자리씩 더하기
            	answer += Character.getNumericValue(arr[i]);
        }

        return answer;
    }
}

나의 경우 문자를 숫자로 변환하는 함수 getNumericmValue() 함수를 찾아 사용했는데 다른 사람들 풀이에는 아스키코드를 이용해 나랑 비슷하게 푼 사람들이 많았다

 

다른사람 코드

import java.util.*;

public class Solution {
    public int solution(int n) {
        int answer = 0;

        char[] arr = Integer.toString(n).toCharArray();

        for(int i = 0; i < arr.length; i++){
            answer += arr[i] - 48;
        }

        return answer;
    }
}

내가 두 줄로 쓴 코드를 tostring() 함수로 한 줄로 만들었다. 배울점

import java.util.*;

public class Solution {
    public int solution(int n) {
        int answer = 0;

        while (n != 0) {
            answer += n % 10;
            n /= 10;
        }

        return answer;
    }
}

그리고 보자마자 내가 이마를 탁 친 코드다

타입변환을 쓰지 않고 수학적으로 해결한 멋진 사람들.....

나머지를 하나씩 더하고 몫만 저장하는 그런 멋진 방법이다........