软件大赛题目----(第十四个)十六进制转换为三进制

来源:互联网 发布:淘宝能赚钱吗 编辑:程序博客网 时间:2024/06/05 21:18

题目为输入一个十六进制,将其转换为三进制,解答如下

package com.bird.software;import java.util.Stack;public class TestConver {public static int sixteenToTen(String num){num = reString(num);int sum = 0;char temp;int tempNum = 0;for(int i = 0; i < num.length(); i++){tempNum = 0;temp = num.charAt(i);switch(temp){case 'A': tempNum = 10;break;case 'B': tempNum = 11;break;case 'C': tempNum = 12;break;case 'D': tempNum = 13;break;case 'E': tempNum = 14;break;case 'F': tempNum = 15;break;default: tempNum = temp - '0';}sum = (int) (sum + tempNum * Math.pow(16, i));}return sum;}public static String reString(String temp){if(temp.length() == 1)return temp;Stack<String> stack = new Stack<String>();for(int i = 0; i < temp.length(); i++){stack.push(String.valueOf(temp.charAt(i)));}StringBuffer str = new StringBuffer();for(int i = 0; i <= stack.size()+1; i++)str.append(stack.pop());System.out.println("-----"+str.toString());return str.toString();}public static String tenToThree(int num){Stack<Integer> stack = new Stack<Integer>();int temp;int shang = 0;while(true){temp = num % 3;shang = num /3;stack.push(temp);if(shang < 3){stack.push(shang);break;}num = shang;}StringBuffer sb = new StringBuffer();for(int i = 0; i <= stack.size()+1; i++){sb.append(stack.pop());}return sb.toString();}public static void main(String[] args) {System.out.print("输入十六进制F对应三进制为    ");System.out.println(tenToThree(sixteenToTen("F")));System.out.println("---------------");System.out.print("输入十六进制5对应三进制为    ");System.out.println(tenToThree(sixteenToTen("5")));}}

输出结果为

输入十六进制F对应三进制为    120---------------输入十六进制5对应三进制为    12


原创粉丝点击