[프로그래머스/C++]Lv.0 - 자릿수 더하기

YH J·2023년 4월 17일
0

프로그래머스

목록 보기
10/168

문제 링크

https://school.programmers.co.kr/learn/courses/30/lessons/120906

내 풀이

n이 1~1000000이므로 1000000부터 나눠서 몫을 더하고 100000, 10000 이런식으로 해서 더해간다. 이렇게 안하고 1의자리부터 10의 나머지를 하면되는데 이상하게함.

내 코드

#include <string>
#include <vector>

using namespace std;

int solution(int n) {
    int answer = 0;
    int a = 1000000;
    for(int i = 0; i < 7; i++)
    {
        answer += n/a;
        if(n/a != 0)
            n -= (n/a)*a;
        a /= 10;
    }
    return answer;
}

다른 사람의 풀이

#include <string>
#include <vector>

using namespace std;

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

다른 사람의 풀이 해석

1의자리수를 더하고 n을 10으로 나누고를 반복

profile
게임 개발자 지망생

0개의 댓글