华为2017年8月30日校招编程真题2-自定义的26进制和十进制之间互相转换
2017-08-30 21:51
1311 查看
题目
二十六进制和十进制之间转换。使用字符-十进制之间的关系
a-1
b-2
…
z-26
aa-27
ab-28
….
huawei-104680767
现在,输入字符串或者整数,要求输出对应的整数或者字符串。
思路
AC(通过70+%,没查出错误)
package test.test2; import org.junit.Test; /** * description: * * @author liyazhou * @since 2017-08-30 19:57 */ public class Main { @Test public void test(){ String[] strs = {"a", "aa", "aaa", "ab", "az", "z", "i", "huawei", "26", "27", "27", "27", "104680767", }; for (String str: strs){ String result = convertTo26(str); System.out.println(str + " :: " + result); } } // public static void main(String[] args){ // Scanner sc = new Scanner(System.in); // String s = sc.next(); // String result = new Main().convertTo26(s); // System.out.println(result); // } public String convertTo26(String str){ char[] chars = str.toCharArray(); String result = ""; if (chars[0] >= '0' && chars[0] <= '9'){ result = numToStr(chars); }else{ result = strToNum(chars) + ""; } return result; } private String numToStr(char[] chars){ StringBuilder result = new StringBuilder(); int num = Integer.valueOf(new String(chars)); while (num != 0){ int re = num % 26; if (re > 0){ char r = (char)(re + ('a' - 1)); result.append(r); } num /= 26; } return result.reverse().toString(); } private int strToNum(char[] chars){ int num = 0; int counter = 0; int base = 1; for (int i = chars.length-1; i >= 0; i --){ base = 1; for (int j = 0; j < counter; j ++){ base *= 26; } num += (chars[i] - 'a' + 1) * base; counter ++; } return num; } }
相关文章推荐
- 华为2017年8月30日校招编程真题01-数字的中文拼音和英文单词之间互相转换
- java中各进制之间的转换(十进制转十六进制、十进制转二进制、二进制转十进制、二进制转十六进制)
- javascript各进制数据与十进制之间的转换
- 十进制(10)与64进制互相转换算法
- 十进制与其他进制之间的转换
- 泛编程中关于std::string类型字符串长度大于预留空间与小于预留空间之间互相转换的探索测试
- C++ 基础编程之十进制转换为任意进制及操作符重载
- 关于各种进制之间互相转化(以十进制为桥梁)
- 设计算法把一个十进制的整数转换成二至九进制之间的任意进制输出
- 十进制与经纬度之间的互相转换
- 整理,C#中二进制,八进制,十六进制 和 十进制之间的互相转换
- 编程实现将任意的十进制整数转换成任意R进制数(R在2-16之间)
- 二进制、十进制、其他进制之间的转换
- Golang 奇葩的时间包之Json与struct对象之间互相转换,JsonDate和JsonTime自定义类型如何实现json编码和解码(二)
- IOS中常用的字符串、十进制、二进制、十六进制之间互相转换及简单算术和
- 利用栈实现把十进制整数转换为二至十六之间的任一进制数的功能
- 二进制,八进制,十进制,小六进制之间的转换
- 【黑马程序员】Java基础01:进制之间的互相转换
- java中各进制之间的转换(十进制转十六进制、十进制转二进制、二进制转十进制、二进制转十六进制)
- Python中不同进制互相转换(二进制、八进制、十进制和十六进制)