大数相乘
前两天,同学说老师布置个作业大数相乘,闲来无事,就写了下
import java.io.*;
import java.util.*;
/*
* 此类为计算大数相乘,大体算法为,将接收到两个数字字符串存放在两个链表中,每个链表的一个节点代表一位数字,
* 链表的顺序是从后往前。然后分别用第二个链表的每一位数字乘以第一个链表的整体,再将得到的链表相加即为所求。
*
*/
public class BigCount
{
public static void main(String[] args)
{
System.out.print("输入第一个数: ");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try
{
String s1 = br.readLine(); //接受字符
System.out.print("输入第二个数: ");
String s2 = br.readLine();
LinkedList<Integer> nl1 = new LinkedList<Integer>();
LinkedList<Integer> nl2 = new LinkedList<Integer>();
//按从后到钱存入链表
for(int i=s1.length()-1;i>=0;i--)
{
nl1.add(Character.getNumericValue(s1.charAt(i)));
}
for(int i=s2.length()-1;i>=0;i--)
{
nl2.add(Character.getNumericValue(s2.charAt(i)));
}
LinkedList<Integer> temp = mul(nl1, nl2);
for(int i=temp.size()-1;i>=0;i--)
{
System.out.print(temp.get(i).intValue());
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
/*
* 计算两链表相乘
*/
public static LinkedList<Integer> mul(LinkedList<Integer> nl1,LinkedList<Integer> nl2)
{
LinkedList<Integer> temp = new LinkedList<Integer>();
LinkedList<Integer> temp0 = null;
temp.add(0);
for(int i=0;i<nl1.size();i++)
{
temp0 = mul(nl2, nl1.get(i).intValue());
//不同位的数字有不同的权值,如123中最后一个3就代表3,2代表20,1代表100
for(int j=0;j<i;j++)
{
temp0 = mul(temp0, 10);
}
temp = plus(temp ,temp0);
}
return temp;
}
/*
* 计算一个链表和一个数相乘
*/
public static LinkedList<Integer> mul(LinkedList<Integer> nl,int k)
{
int temp = 0;
int x;
LinkedList<Integer> tempList = new LinkedList<Integer>();
for(int i=0;i<nl.size();i++)
{
x = nl.get(i).intValue() * k + temp;
tempList.add(x % 10);
temp = x / 10;
}
if(temp != 0)
tempList.add(temp);
return tempList;
}
/*
* 计算机两链表相加
*/
public static LinkedList<Integer> plus(LinkedList<Integer> nl1,LinkedList<Integer> nl2)
{
LinkedList<Integer> nl = new LinkedList<Integer>();
LinkedList<Integer> tempList = new LinkedList<Integer>();
int x;
int temp = 0;
int i;
for(i=0;i<nl1.size() && i<nl2.size();i++)
{
x = nl1.get(i).intValue() + nl2.get(i).intValue() + temp;
nl.add(x % 10);
temp = x / 10;
}
if(i == nl1.size() && i == nl2.size())
{
if(temp != 0)
nl.add(temp);
}
else if(i == nl1.size())
{
for(int j=i;j<nl2.size();j++)
{
tempList.add(nl2.get(j).intValue());
}
tempList = plus(tempList,temp);
for(int j=0;j<tempList.size();j++)
{
nl.add(tempList.get(j).intValue());
}
}
else if(i == nl2.size())
{
for(int j=i;j<nl1.size();j++)
{
tempList.add(nl1.get(j).intValue());
}
tempList = plus(tempList,temp);
for(int j=0;j<tempList.size();j++)
{
nl.add(tempList.get(j).intValue());
}
}
return nl;
}
/*
* 计算一个链表和一个数字相加
*/
public static LinkedList<Integer> plus(LinkedList<Integer> nl,int k)
{
int temp = k;
int x;
for(int i=0;i<nl.size();i++)
{
x = nl.get(i).intValue() + temp;
nl.set(i,x % 10);
temp = x / 10;
}
if(temp != 0)
nl.add(temp);
return nl;
}
}
浙公网安备 33010602011771号