그리디

[백준] 1105. 팔 풀이

hch06 2025. 2. 2. 17:05

https://www.acmicpc.net/problem/1105

 

처음 시작하는 숫자인 L의 8 개수를 먼저 최솟값으로 지정해둔다.
각 자릿수를 검사하다가 8인 자릿수가 나오면 L값에 L과 R의 차 만큼을 더해보아서 해당 자릿수가 8에서 다른 수로 바뀌는지 검사한다.
바뀌면 최솟값을 하나 줄인다.(안바뀌면 숫자가 L에서 R까지 변하는 과정에서 해당 자릿수가 계속 8로 유지됨을 의미)
모든 자릿수 검사 후 최종 최솟값을 출력한다.

 


C

더보기
더보기
#include <stdio.h>

int cnt8(int v){
    int cnt = 0;
    while(v){
        if(v % 10 == 8) cnt++;
        v /= 10;
    }
    return cnt;
}

int main(){
    int l, r; scanf("%d %d", &l, &r);
    int min = cnt8(l);
    int i = 1, tempL = l, v = r - l;
    while(tempL){
        if(tempL % 10 == 8) min -= (v >= i - (l%i)) ? 1 : 0;
        i *= 10; tempL /= 10;
    }
    printf("%d", min);
}

Python

더보기
더보기
def cnt8(v):
    cnt = 0
    while v:
        if v % 10 == 8: cnt += 1
        v //= 10
    return cnt

l, r = map(int, input().split())
min = cnt8(l)
i = 1; tempL = l; v = r - l
while tempL:
    if tempL % 10 == 8: min -= 1 if v >= i - (l%i) else 0 
    i *= 10; tempL //= 10
print(min)

 

'그리디' 카테고리의 다른 글

[백준] 1449. 수리공 항승 풀이  (0) 2025.02.02
[백준] 1138. 한 줄로 서기 풀이  (0) 2025.02.02