首页 > 代码库 > UVA11038- How Many O's?(组合数学)

UVA11038- How Many O's?(组合数学)

题目链接


题意:求出在a到b之间的数中,有多少个0。

思路:组合数学问题。可以枚举每个位置上的数i,假设i之前的数为left,后面的为right,后面有num位数。当i != 0时,将i置为0,所以组合数为left * 10^num(后面的位数,每一位有10种选择),当i = 0时,当前面取[1, left - 1]时,保证组合的数一定小于原来的数,所以后面的可以取10^num,当取left时,后面的数只能取不大于right的数,所以组合数为(left - 1) * (10 ^ num) + right + 1;

代码:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>

using namespace std;

typedef long long ll;

ll a, b;

ll solve(ll left) {
    ll ans = 0, num = 1, right = 0, mid;
    while (left >= 10) {
        mid = left % 10; 
        left /= 10;
        if (mid)
            ans += left * num;
        else
            ans += (left - 1) * num + right + 1;
        right += mid * num;
        num *= 10; 
    }
    return ans;
}

int main() {
    while (scanf("%lld%lld", &a, &b)) {
        if (a == -1 && b == -1)
            break;
        ll ans = solve(b) - solve(a - 1); 
        if (a == 0)
            ans++;
        printf("%lld\n", ans); 
    }    
    return 0;
}


UVA11038- How Many O's?(组合数学)