題目
如題
題解
- 十進制轉八進制:數字每次對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;
}
}