前两天看了b站上狂神的二进制计算教程
动手先写了个二进制加法计算器
通过String和List互转的方式
代码语言:javascript复制//String转List
Arrays.asList(str.split(""))
//List转String
String.join("", list)
基本实现二进制加法功能
代码语言:javascript复制import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* @ClassName: clacdemo
* @Date: 2020/7/7 0007 21:10
* @Description:
* @Author: <achao1441470436@gmail.com>
*/
public class clacdemo {
public static void main(String[] args) {
String four = "00000100";
String five = "00000101";
System.out.println(sum(four, five));
}
/**
* 加法
*
* @param num1
* @param num2
* @return
*/
public static String sum(String num1, String num2) {
List<String> list = new ArrayList<>();
//异或
list.add(xor(num1, num2));
//与
list.add(and(num1, num2));
//如果 与 结果为0
if (isZero(list.get(list.size() - 1))) {
//return 异或 的结果
return list.get(list.size() - 2);
}
//从第二步开始,重复计算
while (true) {
//进位
list.add(carry(list.get(list.size() - 1)));
//异或
list.add(xor(list.get(list.size() - 3), list.get(list.size() - 1)));
//与
list.add(and(list.get(list.size() - 4), list.get(list.size() - 2)));
//如果 与 结果为0
if (isZero(list.get(list.size() - 1))) {
//return 异或 的结果
return list.get(list.size() - 2);
}
}
}
/**
* 异或
*
* @param num1
* @param num2
* @return
*/
public static String xor(String num1, String num2) {
List<String> numList1 = Arrays.asList(num1.split(""));
List<String> numList2 = Arrays.asList(num2.split(""));
List<String> result = new ArrayList<>();
for (int i = 0; i < numList1.size(); i ) {
//异或 如果两者相等为0 不等为1
if (numList1.get(i).equals(numList2.get(i))) {
result.add("0");
} else {
result.add("1");
}
}
return String.join("", result);
}
/**
* 与
*
* @param num1
* @param num2
* @return
*/
public static String and(String num1, String num2) {
List<String> numList1 = Arrays.asList(num1.split(""));
List<String> numList2 = Arrays.asList(num2.split(""));
List<String> result = new ArrayList<>();
for (int i = 0; i < numList1.size(); i ) {
//与 两者为1 结果为1 否则为0
if ("1".equals(numList1.get(i)) && "1".equals(numList2.get(i))) {
result.add("1");
} else {
result.add("0");
}
}
return String.join("", result);
}
/**
* 判断是否全为0
*
* @param num
* @return
*/
public static Boolean isZero(String num) {
List<String> numList = Arrays.asList(num.split(""));
for (String tempNum : numList) {
//判断结果是否含1,有则return false
if ("1".equals(tempNum)) {
return false;
}
}
return true;
}
/**
* 进位
*
* @param num
* @return
*/
public static String carry(String num) {
List<String> numList = Arrays.asList(num.split(""));
for (int i = 0; i < numList.size(); i ) {
if ("1".equals(numList.get(i))) {
try {
numList.set(i - 1, "1");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("溢出!");
System.exit(0);
}
numList.set(i, "0");
}
}
return String.join("", numList);
}
}