[算法]十進制整數轉八進制


題目

如題

題解

  • 十進制轉八進制:數字每次對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