UVA11038 How Many O's?题解
2018-01-16 22:06
399 查看
原文链接:http://www.algorithmist.com/index.php/User:Sweepline/UVa_11038.cpp
AC的C++语言程序如下:
// C++ solution for problem 11038 - "How Many 0's"
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
// Returns the number of zeroes in decimal representation of 0, 1, ..., b.
// Complexity: linear in the number of decimal digits of b.
long long solve(long long b) {
if (b < 0) return 0;
// Compute decimal representation of b
char s[20];
sprintf(s, "%lld", b);
int n = strlen(s);
// Compute powers of 10
long long ten[20] = { 1 };
for (int n = 1; n < 20; n++)
ten
= ten[n-1] * 10;
// Compute suffixes of b.suf[k] = atoll(s+k).
long long suf[20];
suf
= 0;
for (int i = n-1; i >= 0; i--)
suf[i] = suf[i+1] + (s[i] - '0') * ten[n-i-1];
long long res = 1, pref = 0;
for (int k = 1; k < n; k++) {
pref = pref * 10 + (s[k-1] - '0');
// pref is equal to integer, formed by first k digits of b.
if (s[k] != '0')
res += pref * ten[n-k-1];
else
res += (pref - 1) * ten[n-k-1] + suf[k+1] + 1;
}
return res;
}
int main() {
long long m, n;
while (scanf("%lld %lld", &m, &n) == 2 && m >= 0 && n >= 0)
printf("%lld\n", solve(max(m,n)) - solve(min(m,n)-1));
}
AC的C++语言程序如下:
// C++ solution for problem 11038 - "How Many 0's"
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
// Returns the number of zeroes in decimal representation of 0, 1, ..., b.
// Complexity: linear in the number of decimal digits of b.
long long solve(long long b) {
if (b < 0) return 0;
// Compute decimal representation of b
char s[20];
sprintf(s, "%lld", b);
int n = strlen(s);
// Compute powers of 10
long long ten[20] = { 1 };
for (int n = 1; n < 20; n++)
ten
= ten[n-1] * 10;
// Compute suffixes of b.suf[k] = atoll(s+k).
long long suf[20];
suf
= 0;
for (int i = n-1; i >= 0; i--)
suf[i] = suf[i+1] + (s[i] - '0') * ten[n-i-1];
long long res = 1, pref = 0;
for (int k = 1; k < n; k++) {
pref = pref * 10 + (s[k-1] - '0');
// pref is equal to integer, formed by first k digits of b.
if (s[k] != '0')
res += pref * ten[n-k-1];
else
res += (pref - 1) * ten[n-k-1] + suf[k+1] + 1;
}
return res;
}
int main() {
long long m, n;
while (scanf("%lld %lld", &m, &n) == 2 && m >= 0 && n >= 0)
printf("%lld\n", solve(max(m,n)) - solve(min(m,n)-1));
}
相关文章推荐
- Uva 11038 - How Many O's?
- Uva 11038 - How Many O's? 解题报告(计数)
- UVA 11038 How Many O's? (数位统计 )
- UVA 11038 How Many O's?——整数区间分解
- uva 11038 How Many O's? 组合计数
- UVa:11038 How Many O's?
- UVa 11038 - How Many O's? (组合数学 数位统计)
- UVA - 11038 How Many O's? (计数)
- UVa11038 - How Many O's?(数位dp)
- UVa-11038 How Many O's? (整数区间分解)
- UVA11038- How Many O's?(组合数学)
- uva 11038 - How Many O's?(计数问题)
- UVA 11038 - How Many O's? (数学题)
- UVA 11038 - How Many O's?(计数问题)
- uva11038 How Many O's? 数位dp
- UVA11038- How Many O's?(组合数学)
- uva 11038 - How Many O's?
- Uva 10790 - How Many Points of Intersection?
- uva 10061 How many zero's and how many digits ?
- Uva 12216 How Many bases? (数学题)