题目描述:
在计算机中,由于处理器位宽限制,只能处理有限精度的十进制整数加减法,比如在32位宽处理器计算机中,
参与运算的操作数和结果必须在-231~231-1之间。如果需要进行更大范围的十进制整数加法,需要使用特殊
的方式实现,比如使用字符串保存操作数和结果,采取逐位运算的方式。如下:
9876543210 + 1234567890 = ?
让字符串 num1="9876543210",字符串 num2="1234567890",结果保存在字符串 result = "11111111100"。
-9876543210 + (-1234567890) = ?
让字符串 num1="-9876543210",字符串 num2="-1234567890",结果保存在字符串 result = "-11111111100"。
输入描述:
输入两个字符串
输出描述:
输出给求和后的结果
思路一:
import java.math.BigInteger;
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext())
{
BigInteger n1 = scanner.nextBigInteger();
BigInteger n2 = scanner.nextBigInteger();
System.out.println(n1.add(n2));
}
}
}
思路二:
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext())
{
String s1 = scanner.next();
String s2 = scanner.next();
int resultLen = Math.max(s1.length(), s2.length()) + 1;
char[] result = new char[resultLen];
int flag = 0; //同正
if (s1.charAt(0) == '-' && s2.charAt(0) == '-')
{
flag = 1; //同负
s1 = s1.substring(1);
s2 = s2.substring(1);
}
else if (s1.charAt(0) == '-')
{
flag = 2; //num1负,num2正
s1 = s1.substring(1);
}
else if (s2.charAt(0) == '-')
{
flag = 3; //num1正,num2负
s2 = s2.substring(1);
}
//补齐0,方便加减
while (s1.length() < s2.length())
s1 = "0" + s1;
while (s2.length() < s1.length())
s2 = "0" + s2;
if (flag == 0 || flag == 1)
{
resultLen = add(s1, s2, result);
if (flag == 1)
result[--resultLen] = '-';
}
else if (flag == 2)
{
if (more(s1, s2))
{
resultLen = subtract(s1, s2, result);
result[--resultLen] = '-';
}
else
resultLen = subtract(s2, s1, result);
}
else if (flag == 3)
{
if (more(s1, s2))
resultLen = subtract(s1, s2, result);
else
{
resultLen = subtract(s2, s1, result);
result[--resultLen] = '-';
}
}
System.out.println(new String(result).substring(resultLen));
}
}
public static int add(String num1, String num2, char[] result)
{
int index = result.length;
int carry = 0;
int temp = 0;
for (int i = num1.length() - 1; i >= 0; i--)
{
temp = num1.charAt(i) - '0' + num2.charAt(i) - '0' + carry;
if (temp >= 10)
{
carry = temp / 10;
temp = temp % 10;
}
else
carry = 0;
result[--index] = (char)(temp + '0');
}
if (carry > 0)
result[--index] = (char)(carry + '0');
return index;
}
public static boolean more(String num1, String num2)
{
for (int i = 0; i < num1.length(); i++)
{
if (num1.charAt(i) > num2.charAt(i))
return true;
else if (num1.charAt(i) < num2.charAt(i))
return false;
}
return true;
}
public static int subtract(String num1, String num2, char[] result)
{
int index = result.length;
int carry = 0;
int temp = 0;
for (int i = num1.length() - 1; i >= 0; i--)
{
temp = num1.charAt(i) - num2.charAt(i) - carry;
if (temp < 0)
{
carry = 1;
temp = temp + 10;
}
else
carry = 0;
result[--index] = (char)(temp + '0');
}
//相减会出现首位为0的情况,要找到首位不为0的位置
for (; index < result.length; index++)
if (result[index] != '0')
break;
return index;
}
}