給定一個十進製數作為輸入,我們需要編寫一個程序將給定的十進製數轉換為等效的八進製數。即將基值 10 的數字轉換為基值 8。數字係統的基值決定了用於表示數值的位數。例如,二進製數係統使用兩個數字0和1,八進製數係統使用0-7的8個數字,十進製數係統使用0-9的10個數字來表示任何數值。
例子:
Input : 16 Output: 20 Input : 10 Output: 12 Input : 33 Output: 41
算法:
- 將數字除以 8 時的餘數存儲在數組中。
- 現在將這個數字除以 8
- 重複以上兩步,直到數字不等於0。
- 現在以相反的順序打印數組。
例如:
如果給定的十進製數是 16。
步驟1:16 除以 8 餘數為 0,因此 arr[0] = 0。
第2步:將 16 除以 8。新數字為 16/8 = 2。
步驟3:2除以8的餘數為2。因此,arr[1] = 2。
步驟4:2除以8。新數字是2/8 = 0。
步驟5:由於數字變為 = 0。
停止重複步驟並以相反的順序打印數組。因此,等效的八進製數是20。
下圖顯示了將十進製數 33 轉換為等效八進製數的示例。
下麵是上述想法的實現。
C
// C program to convert decimal
// number to octal number
#include <stdio.h>
// function to convert decimal to octal
void decToOctal(int n)
{
// array to store octal number
int octalNum[100];
// counter for octal number array
int i = 0;
while (n != 0) {
// storing remainder in octal array
octalNum[i] = n % 8;
n = n / 8;
i++;
}
// printing octal number array in reverse order
for (int j = i - 1; j >= 0; j--)
printf("%d", octalNum[j]);
}
// Driver Code
int main()
{
int n = 33;
// Function Call
decToOctal(n);
return 0;
}
輸出
41
時間複雜度:O(logN)
空間複雜度:O(N),因為創建數組來存儲八進製數
另一種方法:(O(1) 空間複雜度)
不使用數組也可以使用以下算法解決此問題:
- 將八進製 num 初始化為 0,將 countVal 初始化為 1,將十進製數初始化為 n
- 求小數除以 8 的餘數
- 通過 OctalNum + (餘數 * countval) 更新八進製數
- 將 countval 增加 countval*10
- 小數除以 8
- 從第二步開始重複,直到小數為零
下麵是上述想法的實現:
C
// C program to convert decimal
// number to octal number
#include <stdio.h>
// function to calculate the octal value of the given
// decimal number
void decimaltoOctal(int deciNum)
{
int octalNum = 0, countval = 1;
int dNo = deciNum;
while (deciNum != 0) {
// decimals remainder is calculated
int remainder = deciNum % 8;
// storing the octalvalue
octalNum += remainder * countval;
// storing exponential value
countval = countval * 10;
deciNum /= 8;
}
printf("%d", octalNum);
}
// Driver Code
int main()
{
int n = 33;
// Function Call
decimaltoOctal(n);
return 0;
}
輸出
41
時間複雜度:O(logN)
輔助空間:O(1)
相關用法
- C語言 Atoi()用法及代碼示例
- C語言 Getchar()用法及代碼示例
- C語言 abs()用法及代碼示例
- C語言 printf() and scanf()用法及代碼示例
- C語言 strchr()用法及代碼示例
- C語言 strcpy()用法及代碼示例
- C語言 strcat()用法及代碼示例
- C語言 宏 assert()用法及代碼示例
- C語言 isdigit()用法及代碼示例
- C語言 islower()用法及代碼示例
- C語言 setlocale()用法及代碼示例
- C語言 cos()用法及代碼示例
- C語言 cosh()用法及代碼示例
- C語言 sin()用法及代碼示例
- C語言 sinh()用法及代碼示例
- C語言 tanh()用法及代碼示例
- C語言 exp()用法及代碼示例
- C語言 ldexp()用法及代碼示例
- C語言 log()用法及代碼示例
- C語言 log10()用法及代碼示例
- C語言 pow()用法及代碼示例
- C語言 sqrt()用法及代碼示例
- C語言 ceil()用法及代碼示例
- C語言 fabs()用法及代碼示例
- C語言 floor()用法及代碼示例
注:本文由純淨天空篩選整理自佚名大神的英文原創作品 C Program to Convert Decimal to Octal。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。