[算法]华为笔试题——字母和十进制数映射
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这里)。
代码:
使用字母来表示一个正整数,用小写字母表示。映射规则很简单,如下所示:
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")); } }
相关文章推荐
- 华为2014年四道笔试算法题
- 20150915华为软件笔试题-从m个不同字母中任取n个字目的组合
- 算法题之三道2016华为校招上机笔试题
- 华为2014笔试算法题汇总
- 2014--华为笔试算法汇总
- [算法]华为笔试题——拼音与英文转换
- 【算法】华为笔试_颠倒相加_掷骰子
- [置顶] 华为2014笔试算法题汇总
- 华为上机笔试之通过键盘输入一串小写字母(a~z)组成的字符串。请编写一个字符串压缩程序,将字符串中连续出席的重复字母进行压缩,并输出压缩后的字符串。
- 字符串处理算法(八)将字符串中连续出席的重复字母进行压缩(华为校园招聘题)
- 偶见一道华为笔试题(简单的题更显算法啊--不可忽视的数学)
- 算法与数据结构——华为笔试题
- 剑指offer-算法题练习:part13 数字字母重排序-笔试题
- 算法笔试题
- 华为笔试题目--约瑟夫环(Joseph)修改版
- 用Python实现B2M算法:将二进制文件映射为灰度图片
- 算法--将字符串中*号移到左边,字母移到右边,保持字母相对顺序不变
- 华为笔试题二
- 华为ICDComm通讯控件IP映射(穿透)
- 一些笔试常考简单算法小结