计算两个大数的差
- 条件:
- num1>=num2
- num2>=0
- 思路:在不使用Java自带的BigInteger情况下,可以通过byte数组的形式来完成计算。把数值小和数据大的位数设置一样,通过补0方式。在这巧妙通过'0'=48,使用getBytes()完成最初的数据构成。采用按位减的形式,如果被减数小于减数,则让减数的前一位+1.
public class RepalceBigInteger {
public static void main(String[] args) {
String solution = solution("100-21");
System.out.println(solution);
}
private static String solution(String line) {
String[] nums = line.split("-");
byte[] before = nums[0].getBytes();
byte[] after = nums[1].getBytes();
byte[] temp = new byte[before.length];
int offset = before.length - after.length;
int[] result = new int[before.length];
for (int i = 0; i < temp.length; i++) {
if (i < offset) {
temp[i] = '0';
} else {
temp[i] = after[i - offset];
}
}
for (int i = before.length - 1; i >= 0; i--) {
int beforeNum = before[i];
int afterNum = temp[i];
if (beforeNum >= afterNum) {
result[i] = beforeNum - afterNum;
} else {
int n = temp[i - 1];
temp[i - 1] = (byte) (n + 1);
result[i] = 10 + beforeNum - afterNum;
}
}
StringBuffer sbf = new StringBuffer();
for (int i = 0; i < result.length; i++) {
sbf.append(result[i]);
}
return sbf.toString();
}
}
网友评论