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

}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值