package bigint;

/**
* This class encapsulates a BigInteger, i.e. a positive or negative integer
* with any number of digits, which overcomes the computer storage length
* limitation of an integer.
*
*/
public class BigInteger { /**
* True if this is a negative integer
*/
boolean negative; /**
* Number of digits in this integer
*/
int numDigits; /**
* Reference to the first node of this integer's linked list representation
* NOTE: The linked list stores the Least Significant Digit in the FIRST node.
* For instance, the integer 235 would be stored as: 5 --> 3 --> 2
*
* Insignificant digits are not stored. So the integer 00235 will be stored as:
* 5 --> 3 --> 2 (No zeros after the last 2)
*/
DigitNode front; /**
* Initializes this integer to a positive number with zero digits, in other
* words this is the 0 (zero) valued integer.
*/
public BigInteger() {
negative = false;
numDigits = 0;
front = null;
} /**
* Parses an input integer string into a corresponding BigInteger instance. A
* correctly formatted integer would have an optional sign as the first
* character (no sign means positive), and at least one digit character
* (including zero). Examples of correct format, with corresponding values
* Format Value +0 0 -0 0 +123 123 1023 1023 0012 12 0 0 -123 -123 -001 -1 +000
* 0
*
* Leading and trailing spaces are ignored. So " +123 " will still parse
* correctly, as +123, after ignoring leading and trailing spaces in the input
* string.
*
* Spaces between digits are not ignored. So "12 345" will not parse as an
* integer - the input is incorrectly formatted.
*
* An integer with value 0 will correspond to a null (empty) list - see the
* BigInteger constructor
*
* @param integer Integer string that is to be parsed
* @return BigInteger instance that stores the input integer.
* @throws IllegalArgumentException If input is incorrectly formatted
*/
public static BigInteger parse(String integer) throws IllegalArgumentException { boolean f = false;
/* IMPLEMENT THIS METHOD */
int len = integer.length();
StringBuffer buffer = new StringBuffer(integer).reverse();
char[] cs = buffer.toString().toCharArray();
DigitNode head = null;
DigitNode node1 = new DigitNode(0, null);
DigitNode node2 = new DigitNode(0, null);
head = node1;
for (int i = 0; i < len; i++) {
if (cs[i] == '-') {
f = true;
len--;
continue;
}
if(cs[i] == '+') {
len--;
continue;
}
if (Character.isDigit(cs[i])) {
node2 = new DigitNode(cs[i] - '0', null);
node1.next = node2;
node1 = node2;
} else {
throw new IllegalArgumentException("Incorrect Format");
} }
BigInteger integer2 = new BigInteger();
integer2.front = head.next;
integer2.numDigits = len;
integer2.negative = f;
// following line is a placeholder for compilation
return integer2;
} private static void printList(DigitNode head) {
while (head != null) {
System.out.print(head.digit + " ");
head = head.next;
}
} /**
* Adds the first and second big integers, and returns the result in a NEW
* BigInteger object. DOES NOT MODIFY the input big integers.
*
* NOTE that either or both of the input big integers could be negative. (Which
* means this method can effectively subtract as well.)
*
* @param first First big integer
* @param second Second big integer
* @return Result big integer
*/
public static BigInteger add(BigInteger first, BigInteger second) { /* IMPLEMENT THIS METHOD */
BigInteger bigc = new BigInteger();
bigc.front = new DigitNode(0, null);
int carry = 0;
DigitNode a = (first.front);
DigitNode b = (second.front);
DigitNode head = bigc.front;
DigitNode c = bigc.front;
BigInteger d = null;
for (int i = 0; i < first.numDigits || i < second.numDigits; i++) {
if(b==null) {
b=new DigitNode(0, null);
}
int temp = carry + a.digit + b.digit;
c.digit = temp % 10;
bigc.numDigits++;
d = new BigInteger();
d.front = new DigitNode(0, null);
c.next = d.front;
c = d.front;
carry = temp / 10;
a = a.next;
b = b.next;
} if (carry != 0) {
c.digit = carry;
bigc.numDigits++;
}
bigc.negative=first.negative==second.negative?false:true;
bigc.front = head;
// following line is a placeholder for compilation
return bigc;
} public static DigitNode reverseList(DigitNode head) {
if (head == null || head.next == null)
return head;
DigitNode pre = head;
DigitNode cur = head.next; while (cur != null) {
DigitNode temp = cur.next;
cur.next = pre;
pre = cur;
cur = temp;
} head.next = null;
return head; } /**
* Returns the BigInteger obtained by multiplying the first big integer with the
* second big integer
*
* This method DOES NOT MODIFY either of the input big integers
*
* @param first First big integer
* @param second Second big integer
* @return A new BigInteger which is the product of the first and second big
* integers
*/
public static BigInteger multiply(BigInteger first, BigInteger second) {
DigitNode front2 = second.front;
String retval = front2.digit + "";
for (DigitNode curr = front2.next; curr != null; curr = curr.next) {
if (curr.digit == 0)
continue;
retval = curr.digit + retval;
}
int b=Integer.parseInt(retval);
DigitNode a = (first.front);
BigInteger bigc=new BigInteger();
bigc.front = new DigitNode(0, null);
BigInteger d = null;
DigitNode c = bigc.front;
int carry=0;
for(int i=0;i<first.numDigits;i++){
int temp=a.digit*b+carry;
c.digit=temp%10;
bigc.numDigits++;
d = new BigInteger();
d.front = new DigitNode(0, null);
c.next = d.front;
c = d.front;
carry=temp/10;
a = a.next;
}
while(carry!=0){//乘法的进位可能不止一位
c.digit=carry%10;
bigc.numDigits++;
d = new BigInteger();
d.front = new DigitNode(0, null);
c.next = d.front;
c = d.front;
carry/=10;
}
bigc.negative=first.negative==second.negative?false:true;
// return c;
// following line is a placeholder for compilation
return bigc;
}
public static void main(String[] args) {
BigInteger parse = BigInteger.parse("123");
} public boolean StrToInteger(String str) {
StringBuffer buffer = new StringBuffer(str);
for(int i=0;i<buffer.length();i++) {
if(buffer.charAt(i)=='0') {
return false;
}
}
return true; } /*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
public String toString() {
if (front == null) {
return "0";
}
String retval = front.digit + "";
for (DigitNode curr = front.next; curr != null; curr = curr.next) {
//if (curr.digit == 0&&Integer.parseInt(retval)!=0)
if (curr.digit == 0&&StrToInteger(retval))
continue;
retval = curr.digit + retval;
} if (negative) {
retval = '-' + retval;
}
return retval;
}
}
package bigint;

import java.io.IOException;
import java.util.Scanner; public class BigTest { static Scanner sc; public static void parse()
throws IOException {
System.out.print("\tEnter integer => ");
String integer = sc.nextLine();
try {
BigInteger bigInteger = BigInteger.parse(integer);
System.out.println("\t\tValue = " + bigInteger);
} catch (IllegalArgumentException e) {
System.out.println("\t\tIncorrect Format");
}
} public static void add()
throws IOException {
System.out.print("\tEnter first integer => ");
String integer = sc.nextLine();
BigInteger firstBigInteger = BigInteger.parse(integer); System.out.print("\tEnter second integer => ");
integer = sc.nextLine();
BigInteger secondBigInteger = BigInteger.parse(integer); BigInteger result = BigInteger.add(firstBigInteger,secondBigInteger);
System.out.println("\t\tSum: " + result);
} public static void multiply()
throws IOException {
System.out.print("\tEnter first integer => ");
String integer = sc.nextLine();
BigInteger firstBigInteger = BigInteger.parse(integer); System.out.print("\tEnter second integer => ");
integer = sc.nextLine();
BigInteger secondBigInteger = BigInteger.parse(integer); BigInteger result = BigInteger.multiply(firstBigInteger,secondBigInteger);
System.out.println("\t\tProduct: " + result); } public static void main(String[] args)
throws IOException { // TODO Auto-generated method stub
sc = new Scanner(System.in); char choice;
while ((choice = getChoice()) != 'q') {
switch (choice) {
case 'p' : parse(); break;
case 'a' : add(); break;
case 'm' : multiply(); break;
default: System.out.println("Incorrect choice");
}
}
} private static char getChoice() {
System.out.print("\n(p)arse, (a)dd, (m)ultiply, or (q)uit? => ");
String in = sc.nextLine();
char choice;
if (in == null || in.length() == 0) {
choice = ' ';
} else {
choice = in.toLowerCase().charAt(0);
}
return choice;
} }
package bigint;

/**
* This class encapsulates a linked list for a digit of a big integer.
*
* @author Sesh Venugopal (RU NB CS 112)
*
*/
public class DigitNode {
/**
* The digit
*/
int digit; /**
* Pointer to next digit in the linked list
*/
DigitNode next; /**
* Initializes this digit node with a digit and next pointer
*
* @param digit Digit
* @param next Next pointer
*/
DigitNode(int digit, DigitNode next) {
this.digit = digit;
this.next = next;
} /* (non-Javadoc)
* @see java.lang.Object#toString()
*/
public String toString() {
return digit + "";
}
}

Java大数类 BigInteger的更多相关文章

  1. Java 大数类BigInteger和BigDecimal的基本函数

    在Java中有两个类BigInteger和BigDecimal分别表示不可变的任意精度的整数和不可变的有符号的任意精度的十进制数(浮点数).主要用于高精度计算中.这两个类使得java中的大数,高精度运 ...

  2. JAVA大数类

    JAVA大数类api http://man.ddvip.com/program/java_api_zh/java/math/BigInteger.html#method_summary 不仅仅只能查J ...

  3. ZOJ3477&JAVA大数类

    转:http://blog.csdn.net/sunkun2013/article/details/11822927 import java.util.*; import java.math.BigI ...

  4. JAVA - 大数类详解

    写在前面 对于ACMer来说,java语言最大的优势就是BigInteger,Bigdecimal,String三个类. 这三个类分别是高精度整数,高精度浮点数和字符串,之所以说这个是它的优势是因为j ...

  5. JAVA大数类练手

    今天突然看到了OJ上的大数类题目,由于学习了一点大数类的知识.果断水了6道题......都是非常基础的.就当的练手的吧. 学到的只是一些大数类的基本操作.以后多做点这样的题,争取熟练运用水大数题... ...

  6. Java大数类介绍

    java能处理大数的类有两个高精度大整数BigInteger 和高精度浮点数BigDecimal,这两个类位于java.math包内,要使用它们必须在类前面引用该包:import java.math. ...

  7. HDU高精度总结(java大数类)

      HDU1002   A + B Problem II [题意]大数相加 [链接]http://acm.hdu.edu.cn/showproblem.php?pid=1002 Sample Inpu ...

  8. JAVA大数处理(BigInteger,BigDecimal)

    原文链接 Java中有两个类BigInteger和BigDecimal分别表示大整数类和大浮点数类. 这两个类都在java.math.*包中,因此每次必须在开头处引用该包. Ⅰ基本函数: 1.valu ...

  9. JAVA大数类—基础操作(加减乘除、取模、四舍五入、设置保留位数)

    当基础数据类型长度无法满足需求时可以使用大数类 构造方法接受字符串为参数 BigInteger bInt = new BigInteger("123123"); BigDecima ...

随机推荐

  1. electron中JS报错:require is not defined的问题解决方法

    Electron已经发布了6.0正式版,升级后发现原来能运行的代码报错提示require is not defined 解决办法: 修改创建BrowserWindow部分的相关代码,设置属性webPr ...

  2. Java设计模式的7种设计原则还有很多人不知道

    前言 其实没有设计模式我们也能完成开发工作.但是为什么需要设计模式呢?让你看起来很牛,没错这个算一个.让你的代码层次感分明,可读性强而且容易维护.让你像我一样有更多的摸鱼划水时间. 可能有人说我一个类 ...

  3. 一款 Postman 的开源替代品: Postwoman

    1. 前言 大家都知道,Postman是一个非常受欢迎的API接口调试工具,提供有Chrome扩展插件版和独立的APP,不过它的很多高级功能都需要付费才能使用. 如果你连Postman都还没有用过,不 ...

  4. 第二次作业-titanic数据集练习

    一.读入titanic.xlsx文件,按照教材示例步骤,完成数据清洗. titanic数据集包含11个特征,分别是: Survived:0代表死亡,1代表存活Pclass:乘客所持票类,有三种值(1, ...

  5. 位域-isa指针

    一.isa指针结构 union isa_t { isa_t() { } isa_t(uintptr_t value) : bits(value) { } Class cls; uintptr_t bi ...

  6. [20191213]toad 12下BIND_AWARE提示无效.txt

    [20191213]toad 12下BIND_AWARE提示无效.txt --//链接http://blog.itpub.net/267265/viewspace-2130781/的测试,发现当时测试 ...

  7. Redis中几个简单的概念:缓存穿透/击穿/雪崩,别再被吓唬了

    Redis中几个“看似”高大上的概念,经常有人提到,某些好事者喜欢死扣概念,实战没多少,嘴巴里冒出来的全是高大上的名词,个人一向鄙视概念党,呵呵! 其实这几个概念:缓存穿透/缓存击穿/缓存雪崩,有一个 ...

  8. 【Dos】复制指定文件夹下所有文件到另外指定文件夹下

    bat代码如下: @echo off @set /p fromFile=from: @set /p toFile=to: rem 找到所有文件 dir /b /s %fromFile%\ *.gz & ...

  9. 一 、爬虫的认识与http

    一 .爬虫的认识与http 互联网应用架构  一般采用c/s架构,b/s架构或者m/s架构 c/s 即 client server 客户端 服务端 b/s 即 browser server 浏览器 服 ...

  10. 蒟蒻的PKUWC2019划水记(更新ing)

    前言 (结束再补) \(Dec\ 20th\) 正式出发 今天,是正式出发的日子. 虽说是星期五,可并没有去学校晨跑.难得睡到了\(7\)点,起来匆匆吃完了早饭(一个手抓饼),就出发去火车站了. 到了 ...