题解 UVa11038

题目大意 多组数据,每组数据给定两个非负整数 \(n,m\),请输出将 \(n,m\) 间的所有整数写出来需要多少个零。

分析 考虑使用前缀和。对于每个整数 \(n\),求出 \(0,n\) 写出来需要多少个零,记为 \(num(n)\),则答案为 \(num(m)-num(n-1)\)。对于 \(num(n)\),可以求小于等于 \(n\) 的非负整数在个位、十位······上一共有多少个零,然后累加。

#include<bits/stdc++.h>
using namespace std;

int n, m;

int num(int x)
{
    if(x < 0) return 0;
    
    int res = 0, tot = 1, base = 1;
    while(x) {
        if(x % 10) res += (x / 10) * base;
        else res += (x / 10 - 1) * base + tot;
        tot += x % 10 * base, base *= 10, x /= 10;
    }
    return res + 1;
}

int main()
{   
    while(~scanf("%d%d", &n, &m) && (n != -1 || m != -1))
        printf("%d\n", num(m) - num(n - 1));
}

猜你喜欢

转载自www.cnblogs.com/whx1003/p/12113476.html
今日推荐