我想将整数转换为字母等价,如
HTML中的有序列表.
<ol type="a">
我试图将基数为10的数字转换为带有-z数字的基数26.
但那不是我想要的.
IN WANT GET ----------------------- 1 => a <= a 2 => b <= b 3 => c <= c 4 => d <= d 5 => e <= e 6 => f <= f 7 => g <= g 8 => h <= h 9 => i <= i 10 => j <= j 11 => k <= k 12 => l <= l 13 => m <= m 14 => n <= n 15 => o <= o 16 => p <= p 17 => q <= q 18 => r <= r 19 => s <= s 20 => t <= t 21 => u <= u 22 => v <= v 23 => w <= w 24 => x <= x 25 => y <= y 26 => z <= az 27 => aa <= aa 28 => ab <= ab 29 => ac <= ac
private final static char[] digits = { '0','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' }; private static String numberToAlphaNumeric(long i,int radix) { char[] buf = new char[65]; int charPos = 64; boolean negative = (i < 0); if (!negative) { i = -i; } while (i <= -radix) { buf[charPos--] = digits[(int)(-(i % radix))]; i = i / radix; } buf[charPos] = digits[(int)(-i)]; if (negative) { buf[--charPos] = '-'; } return new String(buf,charPos,(65 - charPos)); } public static String numberToAlphaNumeric(long number) { ArrayList<String> list = new ArrayList<String>(); for( int j = 0; list.size() != number; j++ ) { String alpha = numberToAlphaNumeric( j,digits.length ); if(!alpha.contains( "0" )) { list.add( alpha ); } } return list.get( list.size()-1 ); }
我的第二个想法:
如果我将新的前导符号扩展为数字并将我的数字转换为基数为27的数字,
我在每次携带中都有新的符号,这是错误的,我可以过滤掉它们.
这是非常低效和丑陋的,但我没有更多的想法.常见的方法是什么?
解决方法
这是基本算法.如果您需要更高效,请使用StringBuffer:
public static String getAlpha(int num) { String result = ""; while (num > 0) { num--; // 1 => a,not 0 => a int remainder = num % 26; char digit = (char) (remainder + 97); result = digit + result; num = (num - remainder) / 26; } return result; }