进制转换(附实现)
概念
计算机中一般使用二进制补码存储数据,计算机中的运算都是以补码进行的。
-
二进制数(Binary number):1010B
-
十进制数(Decimal number):1010D
-
十六进制数(Hexdecimal number):1010H
补码:最高位为符号位- 正数:原码与反码相同
- 负数:补码等于原码取反,末尾+1
反码:
- 正数:原码与反码相同
- 负数:原码的数值取反
进制转换
num / x = answer1 …… remain1
answer1 / x = answer2 …… remain2
answer2 / x = answer3 …… remain3
当answer == 0时,得出转换结果,为余数往上数 remain3->remain2->remain1
代码实现
思路
由得出的最后一个余数作为做最高位,由下往上组成结果,想到用先进后出的栈来实现。
不断的往栈中存放余数,当最后的除数为0时,得出答案。
此时从栈中取出位数, 从低往高组成结果。
import java.util.Stack;
class Solution {
public static void main(String[] args) throws Exception {
Stack<Integer> stack = new Stack<Integer>();
stack = DecimalToOther(56, 2);
int size = stack.size();
for (int i = 0; i < size; i++) {
System.out.print(stack.pop());
}
}
//num为要转的十进制数字,x为要转成的进制数
public static Stack<Integer> DecimalToOther(int num, int x) {
Stack<Integer> stack = new Stack<Integer>();
int remain = -1;
while ( num > 0) {
remain = num % x;
num /= x;
stack.push(remain);
}
return stack;
}
}
原码转补码
负数的原码取反+1为补码
正数为其本身
代码实现
class Solution {
public static void main(String[] args) throws Exception {
Stack<Integer> stack = new Stack<Integer>();
stack = DecimalToOther(-10, 2);
int size = stack.size();
for (int i = 0; i < size; i++) {
System.out.print(stack.pop());
}
}
// num为要转的十进制数字,x为要转成的进制数
public static Stack<Integer> DecimalToOther(int num, int x) {
Stack<Integer> stack = new Stack<Integer>();
int remain = -1;
boolean isNegative = false;
if(num < 0) isNegative = true;
num = num > 0 ? num: -num;
//记录位数
int count = 0;
while (num > 0) {
remain = num % x;
num /= x;
stack.push(remain);
}
for (int i = 0; i < 32 - count; i++) {
stack.push(0);
}
if(isNegative)
stack = truefromToComplement(stack);
return stack;
}
//默认进来的数是负数,因为正数的原码等于其本身
public static Stack<Integer> truefromToComplement(Stack<Integer> stack) {
int size = stack.size();
//取反存储用
Stack<Integer> stacktmp = new Stack<Integer>();
int tmp;
//加一存储用
Stack<Integer> stacktmp2 = new Stack<Integer>();
//取反操作,存到res
for (int i = 0; i < size; i++) {
tmp = stack.pop() == 0 ? 1 : 0;
stacktmp.push(tmp);
}
//此时是反序的,所以peak是最终二进制数的最后一位
int plus = 1;
while(stacktmp.size()!= 0 && plus != 0) {
tmp = stacktmp.pop();
if (tmp == 0) {
stacktmp2.push(1);
plus = 0;
}
if (tmp == 1) {
stacktmp2.push(0);
}
}
size = stacktmp2.size();
//将+1后的结果放回去到取反结果中
for (int i = 0; i < size; i++) {
stacktmp.push(stacktmp2.pop());
}
//反序为最终结果返回
size = stacktmp.size();
for (int i = 0; i < size; i++) {
stack.push(stacktmp.pop());
}
return stack;
}
}