您的位置:首页 > 其它

[算法]华为笔试题——字母和十进制数映射

2017-08-31 15:41 549 查看
题目描述:

使用字母来表示一个正整数,用小写字母表示。映射规则很简单,如下所示:

a 1

b 2

...

z 26

aa 27

ab 28

...

huawei 104680767

...

输入描述:

输入字母最少1位,最多6位,且字母只能是小写字母。输入的十进制数不超过32位整数最大值。

判断输入字符串的有效性,若无效输出ERROR。

输出描述:

输入十进制数,返回字母表示的数。输入字母表示的数,返回十进制数。

示例:

输入:

ab

输出:

28

思路:

主要是一个26进制和10进制的转换,26转10很容易,10转26涉及到余数那里需要考虑一下特殊情况(26 % 26 == 0这里)。

代码:

package com;

public class Test2 {
public static String convertTo26(String input) {
String ret = "";
if (input.matches("[1-9]{1}[0-9]{0,}")) {
int inputInt = Integer.parseInt(input);
StringBuilder sb = new StringBuilder();
do{
int temp = inputInt % 26;
if(temp == 0){
//这里需要特殊处理,否则如果是26不会生成z,会生成a`
sb.insert(0, convertChar(26));
inputInt = inputInt / 26 - 1;
}else{
sb.insert(0, convertChar(temp));
inputInt = inputInt / 26;
}
}while(inputInt != 0);
ret = sb.toString();
} else if (input.matches("[a-z]{1,6}")) {
int sum = 0;
for (int i = input.length() - 1; i >= 0; i--) {
sum += convertInt(input.charAt(i)) * Math.pow(26, input.length() - 1 - i);
}
ret = sum + "";
} else {
ret = "ERROR";
}
return ret;
}

/**
* 字符转数字a-1
* @param charactor
* @return
*/
public static int convertInt(char charactor) {
return ((int) (charactor - 'a') + 1);
}

/**
* 数字转字符1-a
* @param num
* @return
*/
public static char convertChar(int num){
return ((char)(num + 'a' - 1));
}

public static void main(String[] args) {
System.out.println(convertTo26("zzz"));
System.out.println(convertTo26("321272407"));
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: