题目1373:整数中1出现的次数(从1到n整数中1出现的次数)
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) {
new Task().solve() ;
}
}
class Task{
InputReader in = new InputReader(System.in) ;
PrintWriter out = new PrintWriter(System.out) ;
long[][] dp = new long[11][10] ;
int[] bit = new int[11] ;
long DP(int pos , int oneSum , boolean isend){
if(pos < 0){
return oneSum ;
}
if(! isend && dp[pos][oneSum] != -1) return dp[pos][oneSum] ;
long sum = 0L ;
int d = isend ? bit[pos] : 9 ;
for(int i = 0 ; i <= d ; i++){
sum += DP(pos-1 , oneSum + ( i == 1 ? 1 : 0) , isend && (i == d)) ;
}
if(! isend) dp[pos][oneSum] = sum ;
return sum ;
}
long sum(long n){
if(n <= 0) return 0L ;
int pos = 0 ;
while(n > 0){
bit[pos++] = (int) ( n% 10) ;
n /= 10 ;
}
return DP(pos-1 , 0 , true) ;
}
void solve(){
for(int i = 0 ; i <= 10 ; i++) Arrays.fill(dp[i] , -1L) ;
while(in.hasNext()){
long l = in.nextLong() ;
long r = in.nextLong() ;
if(l > r){
long t = l ;
l = r ;
r = t ;
}
out.println(sum(r) - sum(l-1));
//out.flush();
}
out.flush();
}
}
class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = new StringTokenizer("");
}
private void eat(String s) {
tokenizer = new StringTokenizer(s);
}
public String nextLine() {
try {
return reader.readLine();
} catch (Exception e) {
return null;
}
}
public boolean hasNext() {
while (!tokenizer.hasMoreTokens()) {
String s = nextLine();
if (s == null)
return false;
eat(s);
}
return true;
}
public String next() {
hasNext();
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public BigInteger nextBigInteger() {
return new BigInteger(next());
}
}