[프로그래머스/C++]Lv.0 - 7의 개수

YH J·2023년 4월 17일
0

프로그래머스

목록 보기
5/168

문제 링크

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

내 풀이

원소 하나마다 while문을 이용하여 1의자리가 7인지 체크하고 10으로 나눈다음 다음 자리 수를 검사하기를 반복한다. 해당 원소가 0이되면 while문을 나가고 다음 원소를 검사한다.

내 코드

#include <string>
#include <vector>
using namespace std;

int solution(vector<int> array) {
    int answer = 0;
    for(int i = 0; i < array.size(); i++)
    {
        while(1)
        {
            if(array[i]==0)
                break;
            if(array[i]%10 == 7)
                answer++;
            array[i] /= 10;
        }
    }
    return answer;
}

다른 사람의 풀이

#include <string>
#include <vector>

using namespace std;

int solution(vector<int> array) {
    int answer = 0;
    for(auto num : array)
    {
        while(num > 0)
        {
            if((num % 10) == 7)
                answer++;
            num = num / 10;
        }
    }
    return answer;
}

다른 사람의 풀이 해석

비슷하나 while의 조건으로 n > 0 을 해두어서 if문 하나를 줄였다.
다른 방법으로는 string으로 변환해서 char 하나마다 '7'인지 검사하는 방법도 있다.

profile
게임 개발자 지망생

0개의 댓글