package chow.test;
/**
* @author Chow
* @date Jun 7, 2010
* @Description 大整数的加法,减法,乘法,除法
*/
public class BigNumOperation {
private static String result;
//加法,从低位加起,逢十进一
public static String add(String firstNum, String secondNum){
result = "";
int maxLength = firstNum.length() >= secondNum.length() ? firstNum.length() : secondNum.length();
int index = maxLength - 1;
int carry = 0;
while(firstNum.length() < maxLength){
firstNum = "0" + firstNum;
}
while(secondNum.length() < maxLength){
secondNum = "0" + secondNum;
}
while(index >= 0){
int firstInt = Integer.valueOf(firstNum.substring(index, index + 1));
int secondInt = Integer.valueOf(secondNum.substring(index, index + 1));
result += (firstInt + secondInt + carry) % 10;
carry = (firstInt + secondInt + carry) / 10;
index--;
}
if(carry != 0){
result += carry;
}
return revert(result);
}
//减法,分三种情况:1.两者相等,返回0,2:大数减小数,小数补0,逐位减,借位;3:小数减大数,转化为2,加-号
public static String minus(String firstNum, String secondNum){
result = "";
String sign = "";
if(firstNum.equals(secondNum)){
return "0";
}
//小数-大数,交换firstNum与secondNum,并符号置为-
if(firstNum.length() < secondNum.length()
|| (firstNum.length() == secondNum.length() && firstNum.compareTo(secondNum) < 0)){
sign = "-";
String tmp = firstNum;
firstNum = secondNum;
secondNum = tmp;
}
//若小数(secondNum)不足位,高位补0
while(secondNum.length() < firstNum.length()){
secondNum = "0" + secondNum;
}
//大数从低位开始,逐位减小数
int index = firstNum.length() - 1;
int borrow = 0; //记录借位
while(index >= 0){
int left = firstNum.charAt(index) - secondNum.charAt(index) + borrow;
if(left < 0){
borrow = -1;
left += 10;
}
result = left + result;
index--;
}
//去除多余的前导0
while(result.indexOf("0") == 0){
result = result.substring(1);
}
return sign + result;
}
//反转字符串
public static String revert(String string){
char[] charArray = new char[string.length()];
for(int i = 0; i < string.length(); i++){
charArray[i] = string.charAt(string.length() - 1 - i);
}
return new String(charArray);
}
public static void main(String[] args){
System.out.println(BigNumOperation.add("4561427489456123", "798754564567343"));
System.out.println(BigNumOperation.minus("5345435435", "543543543543"));
}
}
自己写的大整数的加减乘除法JAVA实现--待完成
最新推荐文章于 2024-08-26 18:41:35 发布