今天写了个关于大整数的保存结构和实现大整数相加的代码(暂时仅限正整数)

来源:互联网 发布:淘宝怎么设置陌生人 编辑:程序博客网 时间:2024/05/02 02:10

我们先来回顾一下,Java拥有的几种基本类型,byte,short,int,long,char,float,double。其中整数类型的有byte,short,int,long这四种。那么,他们的范围是多少呢?byte是1个字节,8位,范围当然是负的2的7次方到正的2的8次方减一(255),以此类推,最大的整数类型(long)不过也才到2的64次方-1(-9223372036854775808L到9223372036854775807L),所以java中有人做了一个叫做BigInteger的类用来处理超长整数的存储与计算,大家可以在java.math.BigInteger中找到。

今天看面试题,瞄到这么一道题,叫模拟这个BigInteger的数据结构来存储超大整数,并实现其加法,不才只想到正整数部分,代码如下:


 

public class TestBig { private String bigNum; private int MAX ; private byte arr[] ; public static void main(String[] args) {  TestBig t1 = new TestBig( "923456999999999999999988888888888888888888888888888888");  TestBig t2 = new TestBig("99754369999999999999999999999999999999999999999999999999999999");  System.out.println(t1.arr.length);  System.out.println(t2.arr.length);  System.out.println(t1.addBig(t2)); } public TestBig(String bigNum){  this.bigNum = bigNum;  this.MAX = bigNum.length();  arr = new byte[MAX];  for (int i = 0; i < arr.length; i++) {   arr[i] = Byte.valueOf(bigNum.substring(i, i+1));  }   } public TestBig addBig(TestBig secBig) {  int LEN = this.MAX>secBig.MAX?this.MAX:secBig.MAX;  int index = LEN - 1;  int jinwei = 0;  String result = "";  while (this.MAX<LEN) {      this.bigNum = "0" + this.bigNum;   this.MAX++;  }  while (secBig.MAX<LEN) {      secBig.bigNum = "0" + secBig.bigNum;   secBig.MAX++;  }  TestBig t1 = new TestBig(this.bigNum);  TestBig t2 = new TestBig(secBig.bigNum);  //System.out.println("t1:"+t1);  //System.out.println("t2:"+t2);  //System.out.println(b1.length);  //System.out.println(b2.length);  //System.out.println("LEN = "+LEN);  //System.out.println("index = "+index);    byte[] b1 = t1.arr;  byte[] b2 = t2.arr;  while (index>=0) {   result = "" + (b1[index] + b2[index]+jinwei)%10 + result;   if (b1[index] + b2[index]+jinwei>=10) {    jinwei = 1;   }else {    jinwei = 0;   }   index--;  }  if (jinwei == 1) {   result = "1" + result;  }  TestBig resBig = new TestBig(result);  return resBig; } @Override public String toString() {  // TODO Auto-generated method stub  return this.bigNum.toString(); } }

原创粉丝点击