java进制转换

对于10进制数转换为N(2-36)进制一般都是选择取余除的算法进行转换 ,下面给出两种方案

一种是递归,一种是迭代。通过效率评价两者性能

其中迭代的方案直接取自java源代码。

/* *Class NotationConvert.java *Create Date: 2009-11-12 *Author:a276202460 */ package com.rich.notation; public class NotationConvert { private static final String[] letters = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f", "g", "h", "i", "g", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z" }; static final char[] digits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' }; public static String TentoN(int value, int number) { if (number <= 1 || number > letters.length) { throw new RuntimeException("Faild"); } if (value < 0) { return "-" + TentoN(0 - value, number); } if (value < number) { return letters[value]; } else { return (TentoN(value / number, number) + letters[value % number]); } } public static String TentoN1(int value, int number) { if (number <= 1 || number > letters.length) { throw new RuntimeException("Faild"); } char[] rs = new char[33]; boolean flag = value < 0; int startindex = 32; if (!flag) value = 0 - value; for (; value <= -number; value /= number) rs[startindex--] = digits[-(value % number)]; rs[startindex] = digits[-value]; if (flag) { rs[--startindex] = '-'; } return new String(rs, startindex, 33 - startindex); } public static void main(String[] s) { long starttime = System.currentTimeMillis(); for (int i = 0; i < 100000; i++) TentoN(-33, 2); System.out.println((System.currentTimeMillis() - starttime)); starttime = System.currentTimeMillis(); for (int i = 0; i < 100000; i++) TentoN1(-33, 2); System.out.println((System.currentTimeMillis() - starttime)); } }   

 

 

 

其中TentoN方法使用了递归的方案进行求解,TentoN1方法使用迭代求解。方案1使用了字符串相加性能上自然会掉一大截,二迭代的方法中经过计算后只需修改char数组的制定索引位置的值,要快的多。

 

 

此程序在本机运行的结果为:

188
31

速度上6倍左右。

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

你可能感兴趣的:(java,c,Date,算法,String,Class)