当前位置:首页 » Project Euler » 详细页

Bouncy numbers 题号:112 难度: 15 中英对照

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%.

Solution

暴力求解法。 显然不存在小于一百的弹跳数,所以当前数i从99开始逐步+1,判断当前数i是不是弹跳数,如果是就bouncy+1; 然后判断bouncy/i有没有到99%,到了就停止,输出结果即可。 那么,如何判断i是不是弹跳数?当前数i mod 10取出一位和上一次取出的位进行比较,判断是否递减或者递增。

Code

public final class p112  {
	
	public static void main(String[] args) {
		long start=System.nanoTime();
        long result = run();        
        long end=System.nanoTime();
        System.out.println(result);
        System.out.println( (end-start)/1000000 + "ms" );
	}
	
	
	public static long run() {
		int bouncy = 0;
		for (int i = 99; ; i++) {
			if (isBouncy(i))
				bouncy++;
			if (bouncy * 100 == i * 99)
				return i;
		}
	}
	
	
	private static boolean isBouncy(int x) {
		if (x < 100)
			return false;
		else {
			boolean nonincreasing = true;
			boolean nondecreasing = true;
			int lastDigit = x % 10;
			x /= 10;
			while (x != 0) {
				int digit = x % 10;
				if (digit > lastDigit)
					nondecreasing = false;
				else if (digit < lastDigit)
					nonincreasing = false;
				lastDigit = digit;
				x /= 10;
			}
			return !nonincreasing && !nondecreasing;
		}
	}
	
}
1587000
26ms