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;
}
}