[算法]十进制整数转八进制

题目

如题

题解

  • 十进制转八进制:数字每次对8取余下是最后一位,然后数字/8,这样依次计算,知道/8=0;借助栈得到最终八进制数。
    另:八进制转十进制:例:八进制:35=>十进制数:5*(80)+3*(81)

代码

import java.util.Scanner;
import java.util.Stack;

public class DecToOct {
	public static void main(String[] args) {
		Scanner s = new Scanner(System.in);
		int num = s.nextInt();
		int octNum = decToOct(num);
		System.out.print(octNum);
	}

	public static int decToOct(int num) {
		int tempNum = num;
		Stack<Integer> stack = new Stack<>();
		while (tempNum != 0) {
			int n = tempNum % 8;
			stack.push(n);
			tempNum /= 8;
		}

		int octNum = 0;
		while (!stack.isEmpty()) {
			int n = stack.pop();
			octNum = octNum * 10 + n;
		}
		return octNum;
	}
}

原文地址:https://www.cnblogs.com/coding-gaga/p/12984485.html