BigInteger——任意进制间的转换及加减乘除取余运算

一、任意进制转换及其他内容

在我们平常做进制转换题目的时候,我们经常会想到先把数转换成十进制再转换成目标进制,然而这样只能应对小数据,对于大数据则得不到目标进制,这篇文章主要讲了BigInteger类的常用方法,其中就有大数据之间进制转换的方法,啥也不说,来看看这个类有啥功能吧!

1,BigInteger属于java.math.BigInteger,因此在每次使用前都要import 这个类。

2,其构造方法有很多,但现在偶用到的有:
BigInteger(String val):将 BigInteger 的十进制字符串表示形式转换为 BigInteger。
BigInteger(String val, int radix):将指定基数的 BigInteger 的字符串表示形式转换为 BigInteger。
如要将int型的2转换为BigInteger型,要写为BigInteger two=new BigInteger(“2”); //注意2双引号不能省略

3,BigInteger类模拟了所有的int型数学操作,如add=="+",divide()==“-”等,但注意其内容进行数学运算时不能直接使用数学运算符进行运算,必须使用其内部方法。而且其操作数也必须为BigInteger型。
如:two.add(2)就是一种错误的操作,因为2没有变为BigInteger型。

4,当要把计算结果输出时应该使用.toString方法将其转换为10进制的字符串,详细说明如下:
String toString():返回此 BigInteger 的十进制字符串表示形式。
输出方法:System.out.print(two.toString());

5,另外说明三个常用到的函数:
BigInteger remainder(BigInteger val):返回其值为 (this % val) 的 BigInteger。
BigInteger negate():返回其值是 (-this) 的 BigInteger。
int compareTo(BigInteger val):将此 BigInteger 与指定的 BigInteger 进行比较。

remainder用来求余数。
negate将操作数变为相反数。
compare的详解如下:
public int compareTo(BigInteger val)将此 BigInteger 与指定的 BigInteger 进行比较。对于针对六个布尔比较运算符 (<, ==, >, >=, !=, <=) 中的每一个运算符的各个方法,优先提供此方法。
执行这些比较的建议语句是:(x.compareTo(y) 0),其中 是六个比较运算符之一。

6.重点掌握:

将BigInteger的数转为2进制:
public class TestChange {
	public static void main(String[] args) {
		System.out.println(change("3",10,2));
	}
//num 要转换的数 from源数的进制 to要转换成的进制
	private static String change(String num,int from, int to){
		return new java.math.BigInteger(num, from).toString(to);
	}
}

二、加减乘除取余运算

如果碰到非常大的数据进行加减乘除取余运算的话,首先想到的就是Integer类,下面就来看看BigInteger的具体实现吧:

package cn.itcast_02;
 
import java.math.BigInteger;
import java.util.Arrays;
 
/*
 * public BigInteger add(BigInteger val):加
 * public BigInteger subtract(BigInteger val):减
 * public BigInteger multiply(BigInteger val):乘
 * public BigInteger divide(BigInteger val):除
 * public BigInteger[] divideAndRemainder(BingInteger val):返回商和余数的数组
 */
public class BigIntegerDemo {
	public static void main(String[] args) {
		BigInteger bi1 = new BigInteger("999");
		BigInteger bi2 = new BigInteger("50");
		
		//public BigInteger add(BigInteger val):加
		System.out.println("add:"+bi1.add(bi2));
		
		//public BigInteger subtract(BigInteger val):减
		System.out.println("subtract:"+bi1.subtract(bi2));
		
		//public BigInteger multiply(BigInteger val):乘
		System.out.println("multiply:"+bi1.multiply(bi2));
		
		//public BigInteger divide(BigInteger val):除
		System.out.println("divide:"+bi1.divide(bi2));
		
		//public BigInteger[] divideAndRemainder(BingInteger val):返回商和余数的数组
		BigInteger[] bis = bi1.divideAndRemainder(bi2);
		System.out.println("divideAndRemainder:"+Arrays.toString(bis));
		System.out.println("商:"+bis[0]);
		System.out.println("余数:"+bis[1]);
	}
 
}
发布了27 篇原创文章 · 获赞 2 · 访问量 931

猜你喜欢

转载自blog.csdn.net/wcy8733996wcy/article/details/104436407