Java统计1到n的自然数中其中字符1出现的次数

用Java代码实现:1到n的自然数中其中 ‘1’  出现的次数,例如:1,11,12,100 中 ‘1’出现了5次。  

该问题的实现关键在于效率问题的考虑,如下是示例代码:

Coding:

/**
 * 统计在从1到n的正整数中1出现的次数
 * 
 * @author 吖大哥
 * @date Jun 11, 2014 10:26:21 PM
 */
public class CountOne {

	public static void main(String[] args) {

		int n = 10000000;

		long start = System.currentTimeMillis();
		int sum1 = CountOne.cnt(n);
		long end = System.currentTimeMillis();

		System.out.println(" sum1 历时 :" + (end - start) + " 出现 1 的次数: " + sum1);

		long start2 = System.currentTimeMillis();
		int sum2 = CountOne.numOF(n);
		long end2 = System.currentTimeMillis();
		System.out.println(" sum2 历时 :" + (end2 - start2) + " 出现 1 的次数: "
				+ sum2);

		long start3 = System.currentTimeMillis();
		int sum3 = CountOne.countNumOf1(n);
		long end3 = System.currentTimeMillis();

		System.out.println(" sum3 历时  :" + (end3 - start3) + "  出现 1 的次数: "
				+ sum3);
	}

	/**
	 * 效率极差
	 * 
	 * @param n
	 * @return
	 */
	public static int cnt(int n) {
		int count = 0;
		String chr = "1";
		while (n >= 1) {
			String str = n + "";
			for (int i = 0; i < str.length(); i++) {
				if (str.indexOf("1") == -1) {// 如果字符串中没1 直接跳出循环
					break;
				}
				if (chr.equals(str.charAt(i) + "")) {
					count++;
				}
			}
			n--;
		}
		return count;
	}

	/**
	 * 效率稍好点
	 * 
	 * @param n
	 * @return
	 */
	public static int numOF(int n) {
		int number = 0;
		for (int i = 1; i <= n; ++i) {
			number += numberOf1(i);
		}
		return number;
	}

	public static int numberOf1(int n) {
		int number = 0;
		while (n != 0) {
			if (n % 10 == 1) {
				number++;
			}
			n = n / 10;
		}
		return number;
	}

	/**
	 * 效率惊人
	 * 
	 * 思路:分别计算 "1" 在每个位上面出现的次数,叠加起来
	 * 
	 * @param n
	 * @return
	 */
	public static int countNumOf1(int n) {
		if (n <= 0) {
			return 0;
		}
		int count = 0;
		int factor = 1;
		while (n / factor != 0) {
			int lowerNum = n - n / factor * factor;
			int currentNum = (n / factor) % 10;
			int highNum = n / (factor * 10);

			if (currentNum == 0) {
				// 如果为0,出现1的次数由高位决定
				count += highNum * factor;
			} else if (currentNum == 1) {
				// 如果为1,出现1的次数由高位和低位决定
				count += highNum * factor + lowerNum + 1;
			} else {
				// 如果大于1,出现1的次数由高位决定
				count += (highNum + 1) * factor;
			}
			factor *= 10;
		}
		return count;
	}

}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值