project euler 112

Bouncy numbers

Working from left-to-right if no digit is exceeded by the digit to its left it is called an increasing number; for example, 134468.

Similarly if no digit is exceeded by the digit to its right it is called a decreasing number; for example, 66420.

We shall call a positive integer that is neither increasing nor decreasing a “bouncy” number; for example, 155349.

Clearly there cannot be any bouncy numbers below one-hundred, but just over half of the numbers below one-thousand (525) are bouncy. In fact, the least number for which the proportion of bouncy numbers first reaches 50% is 538.

Surprisingly, bouncy numbers become more and more common and by the time we reach 21780 the proportion of bouncy numbers is equal to 90%.

Find the least number for which the proportion of bouncy numbers is exactly 99%.


彈跳數

從左往右,如果每一位數字都大於等於其左邊的數字,這樣的數被稱爲上升數,比如134468。

同樣地,如果每一位數字都大於等於其右邊的數字,這樣的數被稱爲下降數,比如66420。

如果一個正整數既不是上升數也不是下降數,我們就稱之爲“彈跳”數,比如155349。

顯然不存在小於一百的彈跳數,而在小於一千的數中有略超過一半(525)的彈跳數。事實上,使得彈跳數的比例恰好達到50%的最小數是538。

令人驚奇的是,彈跳數將變得越來越普遍,到21780時,彈跳數的比例恰好等於90%。

找出使得彈跳數的比例恰好爲99%的最小數。

package projecteuler;

import junit.framework.TestCase;

public class Prj112 extends TestCase {

	public void testBouncyNumbers() {

		int n = Integer.MAX_VALUE;
		int count = 0;
		for (int i = 1; i <= n; i++) {
			if (isBouncyNumber(i)) {
				count++;
			}

			if (i * 99 == 100 * count) {
				System.out.println("i==" + i);
				System.out.println("count=" + count);
				return;
			}
		}
		System.out.println("count=" + (n - count));

	}

	boolean isBouncyNumber(int val) {
		int[] arr = int2Arr(val);
		boolean isDesc = true;
		boolean isAsec = true;
		for (int i = 1; i < arr.length; i++) {

			if (arr[i - 1] < arr[i]) {
				isDesc = false;
			} else if (arr[i - 1] > arr[i]) {
				isAsec = false;
			}

			if (!isDesc && !isAsec) {
				return true;
			}

		}
		return false;
	}

	private int[] int2Arr(int val) {
		String str = Integer.toString(val);
		int[] ret = new int[str.length()];
		for (int i = 0; i < str.length(); i++) {
			ret[i] = Integer.parseInt(String.valueOf(str.charAt(i)));
		}
		return ret;
	}

}


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