首页 > 专题系列 > Java解POJ > POJ 3286 How many 0′s? [解题报告] Java
2013
11-12

POJ 3286 How many 0′s? [解题报告] Java

How many 0′s?

问题描述 :

A Benedict monk No.16 writes down the decimal representations of all natural numbers between and including m and n, mn. How many 0′s will he write down?

输入:

Input consists of a sequence of lines. Each line contains two unsigned 32-bit integers m and n, mn. The last line of input has the value of m negative and this line should not be processed.

输出:

For each line of input print one line of output with one integer number giving the number of 0′s written down by the monk.

样例输入:

10 11
100 200
0 500
1234567890 2345678901
0 4294967295
-1 -1

样例输出:

1
22
92
987654304
3825876150

解题代码:

//* @author: 82638882@163.com
import java.io.*;
public class Main
{
	static long[] a=new long[]{
		1,10,100,1000,10000,100000,1000000,10000000,100000000,1000000000
	};
	static long[] b=new long[]{
		0,1,11,192,2893,38894,488895,5888896,68888897,788888898
	};
	static long[] c=new long[]{
		0,1,20,300,4000,50000,600000,7000000,80000000,900000000
	};
	public static void main(String[] args) throws IOException
	{
		InputStreamReader is=new InputStreamReader(System.in);
		BufferedReader in=new BufferedReader(is);
		while(true)
		{
			String[] ss=in.readLine().split(" ");
			long a=Long.parseLong(ss[0]);
			long b=Long.parseLong(ss[1]);
			if(a==-1&&b==-1)break;
			if(a==0)System.out.println(f(b)+1);
			else System.out.println(f(b)-f(a-1));
		}
	}
	static long f(long w)
	{
		int i;
		long q=w;
		for(i=0;i< 10;i++)
			if(a[i]>w)break;
		long sum=0;
		for(int j=i-1;j>0;j--)
		{
			long u=w/a[j];
			if(u>0)
				sum+=b[j]+(u-1)*c[j];
			w=w%a[j];
		}
		long total=0,oo=0;
		w=q;
		String s=w+"";
		for(int j=1;j< i-1;j++)
		{
			if(w%(a[j]*10)>=a[j]){
				total+=a[j]-1;
				oo+=total;
			}
			else oo+=w%(a[j]*10);
		}
		int bb=0;
		long yy=0;
		for(int g=1;g< s.length();g++)
		{
			if(s.charAt(g)!='0'){
				bb++;
				continue;
			}
			yy+=(Math.pow(10, s.length()-g-1)-1)*bb;
		}
		sum+=oo;
		sum+=yy;
		return sum;	
	}
}

  1. 题目需要求解的是最小值,而且没有考虑可能存在环,比如
    0 0 0 0 0
    1 1 1 1 0
    1 0 0 0 0
    1 0 1 0 1
    1 0 0 0 0
    会陷入死循环

  2. Good task for the group. Hold it up for every yeara??s winner. This is a excellent oppotunity for a lot more enhancement. Indeed, obtaining far better and much better is constantly the crucial. Just like my pal suggests on the truth about ab muscles, he just keeps obtaining much better.

  3. 有一点问题。。后面动态规划的程序中
    int dp[n+1][W+1];
    会报错 提示表达式必须含有常量值。该怎么修改呢。。