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


题目

如题

题解

  • 十进制转八进制:数字每次对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;
	}
}


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM