在 C++ 中將數字轉換為十六進位制
假設我們有一個整數;我們必須設計一個演算法,將其轉換為十六進位制。對於負數,我們將使用二進位制補碼法。
因此,如果輸入像 254 和 -12,則輸出將分別為 fe 和 fffffff4。
為了解決這個問題,我們將遵循以下步驟:
如果 num1 與 0 相同,則 −
返回 "0"
num := num1
s := 空白字串
在 num 為非零時,執行 −
temp := num mod 16
如果 temp <= 9,則 −
s := s + temp 作為數字字元
否則
s := s + temp 作為字母
num := num / 16
反轉陣列 s
返回 s
示例
讓我們看以下實現以獲得更好的理解 −
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
string toHex(int num1){
if (num1 == 0)
return "0";
u_int num = num1;
string s = "";
while (num) {
int temp = num % 16;
if (temp <= 9)
s += (48 + temp);
else
s += (87 + temp);
num = num / 16;
}
reverse(s.begin(), s.end());
return s;
}
};
main(){
Solution ob;
cout << (ob.toHex(254)) << endl;
cout << (ob.toHex(-12));
}輸入
254 -12
輸出
fe fffffff4
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP