簡述:就是你輸入一個頁數,查看從1到你輸入的這一頁,0到9個出現的次數。
有兩種算法:(根據需要而定)
(1)使用計數,即:用一個for循環語句和一個while來統計這幾個數出現的次數
他使用簡單,容易理解,但是效率太低,對於一個小整數而言,他是很好的一個算嗎,但是對於一個100萬以上的數,他的時間往往讓人無法等待,百萬的數就是幾秒中。而千萬級的數,就是幾十秒甚至幾分鐘,,上億時,他的時間就是3或4分鐘。代碼如下:
public static void tongji1()
{
int []tongji=new int[10];
Scanner scanner=new Scanner(System.in);
long yema=scanner.nextLong();
long j1=System.currentTimeMillis();
for(int i=1;i<=yema;i++)
{
int temp=i;
while(temp>0)
{
int n=temp%10;
tongji[n]++;
temp/=10;
}
}
long j2=System.currentTimeMillis();
System.out.println(j2-j1);
}
(2)他不再同二重循環了,因爲i她的時間複雜度太高了,(N方),而他的時間複雜度較低。
他不容易理解,但是效率高,代碼長,他計算一個上億的,就是不再是用毫秒單位計算了,往往使用微妙,上衣的就是幾百圍標,相當於0毫秒,
代碼如下:
public static void tongji2()
{
int []tongji=new int[10];
Scanner scanner=new Scanner(System.in);
long yema=scanner.nextLong();
long j1=System.currentTimeMillis();
int len=0;//計算她的長度-1
long temp=yema;
//將設頁碼是從0開始,並且前面有多餘的0,以你輸入的爲主:990:000-990
tongji[0]=-1;
while(temp>=10)
{
len++;
//減去多餘的0
tongji[0]-=Math.pow(10, len);
temp/=10;
}
jsshu(tongji, len, yema);
long j2=System.currentTimeMillis();
System.out.println(j2-j1);
System.out.println(Arrays.toString(tongji));
}
public static void jsshu(int []a,int len,long yema)
{
if(yema<10)
{
for(int i=0;i<=yema;i++)
{
a[i]++;
}
return;
}
else
{
//10的幾次放
long zuida=(long) Math.pow(10, len);
//統計你輸入的輸的0-9基本變化量,公式:(len-1)*10^(len-2)
long bhl=(long) (len*zuida/10);
int max=(int) (yema/zuida);
long yushu=yema%zuida;
for(int i=0;i<max;i++)
{
a[i]+=zuida;
}
for(int i=0;i<10;i++)
{
a[i]+=max*bhl;
}
if(yushu==0)
{
a[0]+=len;
a[max]++;
}
else
{
int l=0;
//餘數,有沒有少加0;例如70001,餘數1,他中間的令就沒有價
while((zuida/=10)>yushu)
{
l++;
}
a[0]+=(l*(yushu+1));
a[max]+=(yushu+1);
jsshu(a, len-l-1, yushu);
}
}
}
有什麼問題,提出來。能力有限。見諒