十六进制转换的高效算法
2017-11-21 11:16
127 查看
import java.util.Scanner; public class Text { public static void main(String[] args) { System.out.print("Input a decimal number : "); Scanner input=new Scanner(System.in); int decimalNum=input.nextInt(); System.out.println("Hex number is "+decimalToHex(decimalNum)+"H"); System.out.print("Input a hex number : "); String hexNum=input.next(); System.out.println("Decimal number is "+hexToDecimal(hexNum.toUpperCase()));//toUpperCase()使输入的字母可以不区分大小写 } public static String decimalToHex(int decimal) { String hex=""; while(decimal!=0) { int value=decimal%16; hex=toHexChar(value)+hex;//不能简单的hex+=toHexChar(value);因为输出的字符串有顺序 decimal/=16; } return hex; } public static char toHexChar(int hexValue) { if(hexValue>=10&&hexValue<=15) return (char)(hexValue-10+'A'); else return (char)(hexValue+'0'); } public static int hexToDecimal(String hex) { int decimal=0; for(int i=0;i<hex.length();i++) { char hexChar=hex.charAt(i); decimal=decimal*16+hexCharToDecimal(hexChar);//高效算法 } return decimal; } public static int hexCharToDecimal(char ch) { if(ch>='A'&&ch<='F') return ch-'A'+10; else return ch-'0'; } }
相关文章推荐
- M2M算法模型——一种类人,灵活、高效的新型算法设计模型
- C++-蓝桥杯基础训练-第12题-16进制转8进制高效算法
- 13行代码实现最快速最高效的积分图像算法
- 高效判断素数的算法
- 高效求幂取余 算法,复杂度 log(n)
- 构建FP-growth算法高效发现频繁项集
- 求高效算法
- 紫书第八章-----高效算法设计(贪心法)
- 高效算法——G - 贪心
- 高效频繁模式挖掘算法PrePost和FIN的C++源码
- RGB to Gray 高效算法
- JavaScript删除数组重复元素的5个高效算法
- N皇后问题的两个最高效的算法
- 1-2-5组合问题的最高效完整算法
- 一个快速、高效的Levenshtein算法实现
- 算法竞赛入门经典:第八章 高效算法设计 8.12非线性方程求根
- 关键字过滤高效算法
- A,B两个整数集合,设计一个算法求他们的交集,尽可能的高效(牛客网)
- 【两项业界最佳】普林斯顿新算法自动生成高性能神经网络,同时超高效压缩
- [NOIP模拟题][高效算法设计][建模][BFS][记忆化搜索]