超大整數(shù)類型處理工具類(模擬BigInteger的實現(xiàn))

版權(quán)申明

原創(chuàng)文章:本博所有原創(chuàng)文章,歡迎轉(zhuǎn)載,轉(zhuǎn)載請注明出處,并聯(lián)系本人取得授權(quán)。
版權(quán)郵箱地址:banquan@mrdwy.com

介紹一個自己寫的超大整型數(shù)字的處理工具類,主要思路就是把整數(shù)用字符串存儲,然后實現(xiàn)加減乘除等運算方法,運算主要的方式就是拆分成多個整型分別計算,但是要注意處理進位的問題。

package org.tcrow.number;

/**
 * @author tcrow.luo
 *         10進制大數(shù)類型處理類
 */
public class LongLong {

    /**
     * 表示正負,1表示正數(shù),-1表示負數(shù),0表示0
     */
    final int signum;

    /**
     * 拆解大數(shù)字符保存在整形數(shù)組中
     */
    final int[] mag;

    /**
     * 無符號數(shù)的處理常量
     */
    final static long LONG_MASK = 0xffffffffL;

    /**
     * 用于表示十進制
     */
    final static int DEFAULT_RADIX = 10;

    LongLong(int[] mag, int signum) {
        this.mag = mag;
        this.signum = signum;
    }

    public LongLong(String val) {
        int cursor = 0, numDigits;
        final int len = val.length();

        if (len == 0) {
            throw new NumberFormatException("Zero length BigInteger");
        }

        // 檢查大數(shù)符號
        int sign = 1;
        int index1 = val.lastIndexOf('-');
        int index2 = val.lastIndexOf('+');
        if (index1 >= 0) {
            if (index1 != 0 || index2 >= 0) {
                throw new NumberFormatException("Illegal embedded sign character");
            }
            sign = -1;
            cursor = 1;
        } else if (index2 >= 0) {
            if (index2 != 0) {
                throw new NumberFormatException("Illegal embedded sign character");
            }
            cursor = 1;
        }
        if (cursor == len) {
            throw new NumberFormatException("Zero length BigInteger");
        }

        //去掉頭部的0
        while (cursor < len && Character.digit(val.charAt(cursor), DEFAULT_RADIX) == 0) {
            cursor++;
        }

        //沒有發(fā)現(xiàn)有效數(shù)字則直接返回一個值為0的對象
        if (cursor == len) {
            signum = 0;
            mag = new int[0];
            return;
        }

        //計算有效長度
        numDigits = len - cursor;
        signum = sign;

        mag = new int[numDigits];
        while (cursor < len) {
            mag[--numDigits] = Integer.parseInt(val.substring(cursor, ++cursor));
        }
    }

    /**
     * 加法運算
     *
     * @param val
     * @return
     */
    public LongLong add(LongLong val) {
        if (val.signum == 0) {
            return this;
        }
        if (this.signum == 0) {
            return val;
        }

        if (this.signum != val.signum) {
            LongLong thiB = new LongLong(this.toString().replaceAll("-", ""));
            LongLong valB = new LongLong(val.toString().replaceAll("-", ""));
            int compare = compareMagnitude(thiB, valB);
            int sign;
            if (compare == 0) {
                return new LongLong(new int[0], 0);
            }

            if (compare > 0) {
                sign = signum;
            } else {
                sign = val.signum;
            }
            return new LongLong(sub(mag, val.mag), sign);
        }

        return new LongLong(add(mag, val.mag), signum);
    }

    /**
     * 無符號數(shù)相加
     *
     * @param x
     * @param y
     * @return
     */
    private int[] add(int[] x, int[] y) {
        boolean cb = false;
        StringBuffer result = new StringBuffer();

        int len = x.length > y.length ? x.length : y.length;

        for (int i = 0; i < len; i++) {
            //短數(shù)組高位補0
            int thiV = i < x.length ? x[i] : 0;
            int valV = i < y.length ? y[i] : 0;

            result.append((thiV + valV + (cb ? 1 : 0)) % 10);

            if (thiV + valV > 9 || (thiV + valV + (cb ? 1 : 0)) == 10) {
                cb = true;
            } else {
                cb = false;
            }
        }
        if (cb) {
            result.append(1);
        }
        return new LongLong(result.reverse().toString()).mag;
    }

    /**
     * 減法運算
     *
     * @param val
     * @return
     */
    public LongLong sub(LongLong val) {
        if (val.signum == 0) {
            return this;
        }

        if (signum == 0) {
            return val.negate();
        }

        if (this.signum != val.signum) {
            if (this.signum < 0) {
                return new LongLong(val.add(new LongLong(this.toString().replaceFirst("-", ""))).mag, signum);
            }
            return this.add(new LongLong(val.toString().replaceFirst("-", "")));
        }

        int compare = compareMagnitude(this, val);

        if (compare == 0) {
            return new LongLong("0");
        }

        return new LongLong(sub(mag, val.mag), ((compare < 0) ? this.negate().signum : signum));
    }

    /**
     * 無符號數(shù)相減,會自動用大數(shù)減小數(shù),返回大數(shù)減小數(shù)的結(jié)果
     *
     * @param x
     * @param y
     * @return
     */
    private int[] sub(int[] x, int[] y) {
        int compare = compareMagnitude(new LongLong(x, 1), new LongLong(y, 1));
        int[] big;
        int[] little;
        if (compare > 0) {
            big = x;
            little = y;
        } else {
            big = y;
            little = x;
        }

        boolean cb = false;
        StringBuffer result = new StringBuffer();

        int len = big.length > little.length ? big.length : little.length;

        for (int i = 0; i < len; i++) {
            //防止數(shù)組溢出
            int thiV = i < big.length ? big[i] : 0;
            int valV = i < little.length ? little[i] : 0;

            int ret = thiV - valV - (cb ? 1 : 0);

            result.append(ret >= 0 ? ret : (ret + 10));

            if (thiV < valV || isLast(ret, cb)) {
                cb = true;
            } else {
                cb = false;
            }
        }
        return new LongLong(result.reverse().toString()).mag;
    }

    private boolean isLast(int ret, boolean cb) {
        return ret == -1 && cb == true;
    }

    /**
     * 轉(zhuǎn)換成字符串
     *
     * @return
     */
    @Override
    public String toString() {
        if (signum == 0) {
            return "0";
        }
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < mag.length; i++) {
            sb.append(mag[i]);
        }
        return signum >= 0 ? sb.reverse().toString() : "-" + sb.reverse().toString();
    }

    /**
     * 比較兩個數(shù)大小,x == y 返回0 x > y 返回 1 x<y 返回-1
     *
     * @param x
     * @param y
     * @return
     */
    final int compareMagnitude(LongLong x, LongLong y) {
        int[] m1 = x.mag;
        int len1 = m1.length;
        int[] m2 = y.mag;
        int len2 = m2.length;
        if (len1 < len2) {
            return -1;
        }

        if (len1 > len2) {
            return 1;
        }

        for (int i = 0; i < len1; i++) {
            int a = m1[m1.length - 1 - i];
            int b = m2[m2.length - 1 - i];
            if (a != b) {
                return ((a & LONG_MASK) < (b & LONG_MASK)) ? -1 : 1;
            }
        }
        return 0;
    }

    /**
     * 反轉(zhuǎn)符號
     *
     * @return
     */
    public LongLong negate() {
        return new LongLong(this.mag, -this.signum);
    }

}

附送單元測試代碼

import com.google.common.base.Stopwatch;
import org.junit.Assert;
import org.junit.Test;
import org.tcrow.number.LongLong;

import java.math.BigInteger;

/**
 * @author tcrow.luo
 * @date 2018/8/17
 * @description
 */
public class TestLongLong {

    @Test
    public void test() throws Exception {
        for (int i = 0; i < 10; i++) {
            for (int j = 0; j < 1000; j++) {
                BigInteger bigInteger = new BigInteger("" + i).add(new BigInteger("" + j));
                LongLong longLong = new LongLong("" + i).add(new LongLong("" + j));
                if (!bigInteger.toString().equals(longLong.toString())) {
                    throw new Exception("i:" + i + "| j:" + j);
                }
                bigInteger = new BigInteger("" + i).subtract(new BigInteger("" + j));
                longLong = new LongLong("" + i).sub(new LongLong("" + j));
                if (!bigInteger.toString().equals(longLong.toString())) {
                    throw new Exception("i:" + i + "| j:" + j);
                }
            }
        }

        for (int i = 0; i < 1000; i++) {
            for (int j = 0; j > -10; j--) {
                BigInteger bigInteger = new BigInteger("" + i).add(new BigInteger("" + j));
                LongLong longLong = new LongLong("" + i).add(new LongLong("" + j));
                if (!bigInteger.toString().equals(longLong.toString())) {
                    throw new Exception("i:" + i + "| j:" + j);
                }
                bigInteger = new BigInteger("" + i).subtract(new BigInteger("" + j));
                longLong = new LongLong("" + i).sub(new LongLong("" + j));
                if (!bigInteger.toString().equals(longLong.toString())) {
                    throw new Exception("i:" + i + "| j:" + j);
                }
            }
        }

    }

    @Test
    public void testBig(){
        Stopwatch stopwatch = Stopwatch.createStarted();
        Assert.assertEquals(new BigInteger("111111111111111111111111111111111111").add(new BigInteger("99999999999999999999999999999")).toString(),new LongLong("111111111111111111111111111111111111").add(new LongLong("99999999999999999999999999999")).toString());
        Assert.assertEquals(new BigInteger("-111111111111111111111111111111111111").add(new BigInteger("99999999999999999999999999999")).toString(),new LongLong("-111111111111111111111111111111111111").add(new LongLong("99999999999999999999999999999")).toString());
        Assert.assertEquals(new BigInteger("-111111111111111111111111111111111111").add(new BigInteger("-99999999999999999999999999999")).toString(),new LongLong("-111111111111111111111111111111111111").add(new LongLong("-99999999999999999999999999999")).toString());
        Assert.assertEquals(new BigInteger("123153534534213414123").add(new BigInteger("-99999999999999999999999999999")).toString(),new LongLong("123153534534213414123").add(new LongLong("-99999999999999999999999999999")).toString());
        Assert.assertEquals(new BigInteger("111111111111111111111111111111111111").subtract(new BigInteger("99999999999999999999999999999")).toString(),new LongLong("111111111111111111111111111111111111").sub(new LongLong("99999999999999999999999999999")).toString());
        Assert.assertEquals(new BigInteger("-111111111111111111111111111111111111").subtract(new BigInteger("-99999999999999999999999999999")).toString(),new LongLong("-111111111111111111111111111111111111").sub(new LongLong("-99999999999999999999999999999")).toString());
        Assert.assertEquals(new BigInteger("111111111111111111111111111111111111").subtract(new BigInteger("-99999999999999999999999999999")).toString(),new LongLong("111111111111111111111111111111111111").sub(new LongLong("-99999999999999999999999999999")).toString());
        Assert.assertEquals(new BigInteger("-111111111111111111111111111111111111").subtract(new BigInteger("99999999999999999999999999999")).toString(),new LongLong("-111111111111111111111111111111111111").sub(new LongLong("99999999999999999999999999999")).toString());
        stopwatch.stop();
        System.out.println(stopwatch.toString());
    }

    @Test
    public void testSingle(){
        LongLong longLong = new LongLong("1");
        System.out.println(new LongLong("-1").sub(new LongLong("2")).toString());
    }
}

相關(guān)代碼已經(jīng)在我的github上面開源了,有興趣可以關(guān)注一下這個項目,主要是做了一些算法的功能實現(xiàn)
https://github.com/tcrow/algorithm

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容