Problem 40

算法描述:

An irrational decimal fraction is created by concatenating the positive integers:

0.123456789101112131415161718192021...

It can be seen that the 12th digit of the fractional part is 1.

If dn represents the nth digit of the fractional part, find the value of the following expression.

d1×d10×d100×d1000×d10000×d100000×d1000000


 

解決問題:

這題目也是運用數學規律

1 2 3 4 5 6 7 8 9 都只有一位,一共9位數

10  11  12  13 。。。99 都只有兩位,一共有 180位數

100  101 。。。。。999 都只有三位,一共有2700位數

以爲第191位爲例子

是0

 

解題過程:

191 = 9 + 180 + 2  則爲從100開始數的第二位,處於的數爲100+1/3 = 100, 在具體得到的數的位置爲1%3=1 爲什麼是1?因爲本來應該從第0位算的,但是這裏得到的是從1開始的。

193 = 9 + 180 + 4  則爲從100開始數的第四位,處於的數爲100 + 3/3 = 101,具體偏移爲3%3=0

198 = 9 + 180 + 9  則爲從100開始的第七位嗎,處於的數爲100+8/3=102,具體偏移爲8%3==2

 

 

 

 

public class Problem40 {

	public static int getElement(int number){
		int cur = 9;
		int digits = 1;
		int start = 1;
		int pos ;
		while(number>cur*digits){
			number  -= cur*digits;
			cur *= 10;
			digits++;
			start *= 10;
		}
		number--;
		int tmp = number;
		number = tmp/digits;
		pos = tmp%digits;
		
		number = start + number;
		int ans;
		
		int i=0;
		do{
			ans = number/start;
			number = number - ans*start;
			start = start/10;
			i++;
//			System.out.println("Start:"+start+"Ans:"+ans);
		}while(i<pos+1);
		
		return ans;
	}
	
	public static void main(String[] args){
		int i=1;
		int result = 1;
		do{
			int tmp = getElement(i);
			result *= tmp;
			System.out.println("i:"+i);
			i*=10;
		}while(i!=10000000);
		System.out.println(result);
	}
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章