编程之美-1的数目 解法及性能比较

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.logging.Handler;

import javax.swing.text.StyledEditorKit.ForegroundAction;

public class Chapter1 {
	public static void main(String[] args) throws NumberFormatException,
			IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		String line;
		System.out.print("input==>");
		while ((line = br.readLine()) != null) {
			if (line.trim().equals("q"))
				break;
			int n = 0;
			try {
				n = Integer.parseInt(line);
			} catch (Exception e) {
				System.out.println("input error");
				System.out.print("input==>");
				continue;
			}
			System.out.println("-----------handle1-----------------");
			long start = System.currentTimeMillis();
			System.out.println("1 total count:"+handle1(n));
			System.out.println("total time:"
					+ (System.currentTimeMillis() - start));
			System.out.println("-----------handle2-----------------");
			start = System.currentTimeMillis();
			System.out.println("1 total count:"+handle2(n));
			System.out.println("total time:"
					+ (System.currentTimeMillis() - start));
			System.out.print("input==>");
		}
	}

	// ///解法1
	public static int handle2(int n) {
		int result = 0;
		for (int i = 1; i <= n; i++) {
			int temp = count2(i);
			result += temp;
		}
		return result;
	}

	public static int count2(int n) {
		int count = 0;
		while (n != 0) {
			count += (n % 10 == 1) ? 1 : 0;
			n /= 10;
		}
		return count;
	}

	// /解法2//
	public static int handle1(int n) {
		int result = 0;
		for (int i = 1; i <= n; i++) {
			int temp = count1(new Integer(i).toString());
			result += temp;
		}
		return result;
	}

	public static int count1(String str) {
		int result = 0;
		for (int i = 0; i < str.length(); i++) {
			char c = str.charAt(i);
			if (c == '1')
				result++;
		}
		return result;
	}

}

输出结果:

input==>100000000
-----------handle1-----------------
1 total count:80000001
total time:11656
-----------handle2-----------------
1 total count:80000001
total time:8937
input==>



 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值