📜  Java中的 BigInteger shiftLeft() 方法

📅  最后修改于: 2022-05-13 01:54:23.082000             🧑  作者: Mango

Java中的 BigInteger shiftLeft() 方法

Java.math.BigInteger.shiftLeft(int n)方法返回一个 BigInteger,其值为 (this << n)。移位距离 n 可能为负数,在这种情况下,此方法执行右 shift.shiftLeft() 方法会将数字二进制表示中的每个数字左移 n 次,并且移位方向的最后一位被替换为0. 这个 ShiftLeft() 方法计算floor(this * 2^n)

句法:

public BigInteger shiftLeft(int n)

参数:该方法接受一个整数类型的参数n ,表示移位距离,以位为单位。

返回值:该方法将位左移n次后返回BigInteger。

异常:如果移位距离为 Integer.MIN_VALUE,该方法可能会抛出ArithmeticException

例子:

Input: value = 2300, shift distance = 3
Output: 18400
Explanation:
Binary Representation of 2300 = 100011111100
shift distance = 3
after shifting 100011111100 left 3 times then
Binary Representation becomes 100011111100000
and Decimal equivalent of 100011111100000 is 18400.

Another way of expressing the same can be 2300*(2^3)=18400

Input: value = 35000, index = 5
Output: 1120000

下面的程序说明了 BigInteger 的 shiftLeft(index) 方法。

// Program to demonstrate shiftLeft() method of BigInteger 
  
import java.math.*;
  
public class GFG {
  
    public static void main(String[] args)
    {
  
        // Creating BigInteger object
        BigInteger biginteger = new BigInteger("2300");
  
        // Creating a int i for Shift Distance
        int i = 3;
  
        // Call shiftLeft() method on bigInteger at index i
        // store the return value as BigInteger
        BigInteger changedvalue = biginteger.shiftLeft(i);
  
        String result = "After applying ShiftLeft by Shift Distance " + i
                        + " on " + biginteger + " New Value is " + changedvalue;
  
        // Printing result
        System.out.println(result);
    }
}
输出:
After applying ShiftLeft by Shift Distance 3 on 2300 New Value is 18400

参考: https: Java/math/BigInteger.html#shiftLeft(int)