Problem E: How many 0's?
A Benedict monk No. 16 writes down the decimal representations of allnatural numbers between and including m and n, m≤ n. How many 0's will he write down?Input consists of a sequence of lines. Each line contains twounsigned 32-bit integersm and n, m ≤n. The last line of input has the value ofm negativeand this line should not be processed.
For each line of input print one line of output with one integer numbergiving the number of 0's written down by the monk.
Sample input
10 11 100 200 0 500 1234567890 2345678901 0 4294967295 -1 -1
Output for sample input
1 22 92 987654304 3825876150
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.StreamTokenizer;
public class Main {
public static final boolean DEBUG = false;
public StreamTokenizer tokenizer;
public BufferedReader cin;
public PrintWriter cout;
public long m, n;
public void init()
{
try {
if (DEBUG) {
cin = new BufferedReader(new InputStreamReader(
new FileInputStream("d:\\OJ\\uva_in.txt")));
} else {
cin = new BufferedReader(new InputStreamReader(System.in));
}
cout = new PrintWriter(new OutputStreamWriter(System.out));
tokenizer = new StreamTokenizer(cin);
tokenizer.resetSyntax();
tokenizer.wordChars('a', 'z');
tokenizer.wordChars('A', 'Z');
tokenizer.wordChars('0', '9');
tokenizer.wordChars(128 + 32, 255);
tokenizer.wordChars('-', '-');
tokenizer.whitespaceChars(0, ' ');
tokenizer.commentChar('/');
tokenizer.quoteChar('"');
tokenizer.quoteChar('\'');
} catch (Exception e) {
e.printStackTrace();
}
}
public String next()
{
try {
tokenizer.nextToken();
if (tokenizer.ttype == StreamTokenizer.TT_EOF) return null;
else if (tokenizer.ttype == StreamTokenizer.TT_WORD) return tokenizer.sval;
else if (tokenizer.ttype == StreamTokenizer.TT_NUMBER) return String.valueOf((int)tokenizer.nval);
else return null;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public boolean input()
{
m = Long.parseLong(next());
n = Long.parseLong(next());
if (m < 0) return false;
return true;
}
public long cal(long x)
{
long lFactor = 1;
long lLow, lCur, lHigh;
long ans = 0;
if (x < 10) return 1;
while (x / lFactor != 0) {
lLow = x % lFactor;
lCur = x / lFactor % 10;
lHigh = x / lFactor / 10;
if (lHigh < 0) break;
if (lFactor < 10) {
ans += lHigh + 1;
} else {
if (lCur == 0) {
ans += (lHigh - 1) * lFactor + lLow + 1;
} else {
ans += lHigh * lFactor;
}
}
lFactor *= 10;
}
return ans;
}
public void solve()
{
long h = cal(n);
long l = (m == 0 ? 0 : cal(m - 1));
long ans = h - l;
cout.println(ans);
cout.flush();
}
public static void main(String[] args) {
Main solver = new Main();
solver.init();
while (solver.input()) {
solver.solve();
}
}
}