求一个数是几位数

     在看《数据结构与算法分析》的基数排序时,用到了数字是几位数,最开始我是直接用字符串来计算的,后来想了想,还是到网上找了找答案,把答案的列出的五种方法分别实现了下,看看各自花费的时间。


  下面的五种方法是csdn的一个问题帖子上别人回复的,怎么找不到原帖了。

package com.test;

import java.math.BigInteger;

//求一个数十几位数
//a = 999999999
//N = 100000000
//time1 = 10141  //3
//time2 = 4531   //1
//time3 = 12781  //5
//time4 = 11688  //4
//time5 = 5343   //2



public class Arithmetic_1 {

	//字符串:第三
	private int get1(long a){
		int count = String.valueOf(a).length();  //最开始尝试使用这个方法
		return count;
	}
	
	//log方法:难道还是这个方法消耗时间最少
	private int get2(long a){
		int count = (int) (Math.log10(a) + 1);
		return count;
	}
	
	//循环:第五
	private int get3(long a){
		int count = 0;
		do {
			count ++;
		} while ((a /= 10) > 0);
		return count;
	}
	
	//递归调用:第四
	private int get4(long a){
		int count = 0;
		count = a < 10 ? 1 : 1 + get4(a/10);
		return count;
	}
	
	//查表法:这个第二
	private int get5(long a){
		//0,10,100,1000,10000,100000,1000000,10000000,100000000,1000000000
		int[] table = {0x0, 0xa, 0x64, 0x3e8, 0x2710, 0x186A0, 0xF4240, 0x989680, 0x5F5E100,
				0x3B9ACA00};//最小几位数的十六进制
		for(int i = 0; i < table.length; i++){
			if(a >= table[i] && a < table[i + 1]){
				return i+1;
			}
		}
		return 0;
	}
	
	public static void main(String[] args) {
		System.out.println("start");
		Arithmetic_1 arith = new Arithmetic_1();
		
		long a = 999999999; //9位数
		
		
		int N = 100000000;
		
		BigInteger begin1 = new BigInteger(""+System.currentTimeMillis());
		for(int i = 0; i < N; i ++){
			arith.get1(a);
		}				
		BigInteger end1 = new BigInteger(""+System.currentTimeMillis());
		System.out.println("time1 = " + end1.subtract(begin1));
		System.out.println();
		
		BigInteger begin2 = new BigInteger(""+System.currentTimeMillis());
		for(int i = 0; i < N; i ++){  //这里加循环是因为一次操作,时间太少,不好比较五种方法的所花费的时间
			arith.get2(a);
		}
		BigInteger end2 = new BigInteger(""+System.currentTimeMillis());
		System.out.println("time2 = " + end2.subtract(begin2));
		System.out.println();
		
		BigInteger begin3 = new BigInteger(""+System.currentTimeMillis());
		for(int i = 0; i < N; i ++){
			arith.get3(a);
		}
		BigInteger end3 = new BigInteger(""+System.currentTimeMillis());
		System.out.println("time3 = " + end3.subtract(begin3));
		System.out.println();
		
		BigInteger begin4 = new BigInteger(""+System.currentTimeMillis());
		for(int i = 0; i < N; i ++){
			arith.get4(a);
		}
		BigInteger end4 = new BigInteger(""+System.currentTimeMillis());
		System.out.println("time4 = " + end4.subtract(begin4));
		System.out.println();
		
		BigInteger begin5 = new BigInteger(""+System.currentTimeMillis());
		for(int i = 0; i < N; i ++){
			arith.get5(a);
		}
		BigInteger end5 = new BigInteger(""+System.currentTimeMillis());
		System.out.println("time5 = " + end5.subtract(begin5));
		System.out.println();
	}

}

你可能感兴趣的:(求一个数是几位数)