本文主要是介绍十六进制转为八进制,java实现,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
问题描述:给定n个十六进制正整数,输出它们对应的八进制数。数据可控范围为long类型。
样例输入
2
39
123ABC
样例输出
71
4435274
解题思路:先把十六进制数转换为十进制数,再把十进制数转换为八进制数。
import java.util.Scanner;/*** @author tastebud*十六进制转换为八进制(比较小的数操作)*/
public class Main {public static void main(String[] args) {//测试用例输入Scanner scanner = new Scanner(System.in);int n = scanner.nextInt();String[] strs = new String[n];int u = n;while (u-- > 0) strs[u] = scanner.next();//nums数组存放十进制数long[] nums = new long[n]; for (int i = n - 1; i > -1; i--) for (int j = 0; j < strs[i].length(); j++) switch (strs[i].charAt(j)) {case 'A':nums[n-i-1] += 10 * Math.pow(16, strs[i].length()-j-1);break;case 'B':nums[n-i-1] += 11 * Math.pow(16, strs[i].length()-j-1);break;case 'C':nums[n-i-1] += 12 * Math.pow(16, strs[i].length()-j-1);break;case 'D':nums[n-i-1] += 13 * Math.pow(16, strs[i].length()-j-1);break;case 'E':nums[n-i-1] += 14 * Math.pow(16, strs[i].length()-j-1);break;case 'F':nums[n-i-1] += 15 * Math.pow(16, strs[i].length()-j-1);break;default:nums[n-i-1] += (strs[i].charAt(j)-48) * Math.pow(16, strs[i].length()-j-1);break;}//s数组存放八进制数Stack[] s = new Stack[n];for (int j = 0; j < nums.length; j++) {s[j] = new Stack();while (nums[j] > 0) {s[j].push(nums[j] % 8);nums[j] /= 8;}while (!s[j].isEmpty()) System.out.print(s[j].pop());System.out.println();}scanner.close();}}class Node{private long element;private Node next;public Node(long ele, Node next) {this.element = ele;this.next = next;}public long getData() {return element;}public Node getNext() {return next;}
}class Stack{private Node top;//链表首结点引用private int size;//栈的大小public Stack() {top = null;size = 0;}public boolean isEmpty() {return size == 0;}public void push(long e) {Node q = new Node(e, top);top = q;size++;}public long pop() {long obj = top.getData();top = top.getNext();size--;return obj;}
}
这篇关于十六进制转为八进制,java实现的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!