String to biginteger java
Класс BigInteger на Java
Класс BigInteger используется для математической операции, которая включает в себя очень большие целочисленные вычисления, выходящие за пределы всех доступных примитивных типов данных.
Например, факториал 100 содержит 158 цифр, поэтому мы не можем сохранить его в любом доступном примитивном типе данных. Мы можем хранить в нем столько целых чисел, сколько захотим. Нет теоретического ограничения на верхнюю границу диапазона, потому что память распределяется динамически, но практически, поскольку память ограничена, вы можете хранить число, в котором содержится число бит Integer.MAX_VALUE, которого должно быть достаточно для хранения в основном всех больших значений.
Ниже приведен пример Java-программы, которая использует BigInteger для вычисления Factorial.
// Java-программа для поиска больших факториалов с использованием BigInteger
import java.math.BigInteger;
import java.util.Scanner;
public class Example
// Возвращает Факториал Н
static BigInteger factorial( int N)
BigInteger f = new BigInteger( «1» ); // Или BigInteger.ONE
// Умножаем f на 2, 3, . N
for ( int i = 2; i
public static void main(String args[]) throws Exception
Если нам нужно написать вышеуказанную программу на C ++, это было бы слишком большим и сложным, мы можем взглянуть на Factorial of Large Number .
Таким образом, класс BigInteger очень удобен в использовании из-за его большой библиотеки методов, и он также широко используется в конкурентном программировании.
Ниже приведен список простых утверждений в примитивной арифметике и аналогичных им выражений в терминах объектов BigInteger.
декларация
Инициализация:
И для целых чисел, доступных как строка, вы можете инициализировать их как:
Некоторые константы также определены в классе BigInteger для простоты инициализации:
Другими подобными функциями являются subtract (), multiply (), div (), remainder ()
Но все эти функции принимают BigInteger в качестве аргумента, поэтому, если мы хотим, чтобы эти операции с целыми числами или строки преобразовывали их в BigInteger, прежде чем передавать их в функции, как показано ниже:
Извлечение значения из BigInteger:
На самом деле CompareTo возвращает -1 (меньше), 0 (равно), 1 (больше) в соответствии со значениями.
Для равенства мы также можем использовать:
Методы класса BigInteger:
- BigInteger abs () : этот метод возвращает BigInteger, значение которого является абсолютным значением этого BigInteger.
- BigInteger add (BigInteger val) : этот метод возвращает BigInteger со значением (this + val).
- BigInteger и (BigInteger val) : этот метод возвращает BigInteger со значением (this & val).
- BigInteger andNot (BigInteger val) : этот метод возвращает BigInteger, значение которого (this &
val).
this).
SPOJ Проблемы:
Таким образом, после вышеупомянутого знания функции класса BigInteger, мы можем легко решить многие сложные проблемы, но помните, что класс BigInteger для обработки внутренне использует массив целых чисел, операция над объектом BigIntegers выполняется не так быстро, как над примитивами, что является функцией добавления в BigIntgers. не требует постоянного времени, это занимает время, пропорциональное длине BigInteger, поэтому сложность программы будет меняться соответственно. Ниже приведены проблемы SPOJ, чтобы понять BigIntegers.
Эта статья предоставлена Уткаршем Триведи. Пожалуйста, напишите комментарии, если вы обнаружите что-то неправильное, или вы хотите поделиться дополнительной информацией по обсуждаемой теме
String to biginteger java
Converting a String to an int , or its respective wrapper class Integer , is a common and simple operation. The same goes for the other way around, converting a Integer to String.
There are multiple ways to achieve this simple conversion using methods built-in to the JDK.
Converting String to Integer
For converting String to Integer or int, there are four built-in approaches. The wrapper class Integer provides a few methods specifically for this use — parseInt() , valueOf() and decode() , although we can also use its constructor and pass a String into it.
These three methods have different return types:
- parseInt() — returns primitive int .
- valueOf() — returns a new or cached instance of Integer
- decode() — returns a new or cached instance of Integer
That being said, it’s valid to raise a question:
«What’s the difference between valueOf() and decode() then?
The difference is that decode() also accepts other number representations, other than regular decimal — hex digits, octal digits, etc.
Note: It’s better practice to instantiate an Integer with the help of the valueOf() method rather than relying on the constructor. This is because the valueOf() method will return a cached copy for any value between -128 and 127 inclusive, and by doing so will reduce the memory footprint.
Integer.parseInt()
The parseInt() method ships in two flavors:
- parseInt(String s) — Accepting the String we’d like to parse
- parseInt(String s, int radix) — Accepting the String as well as the base of the numeration system
The parseInt() method converts the input String into a primitive int and throws a NumberFormatException if the String cannot be converted:
Running this piece of code will yield:
Integer.valueOf()
The valueOf() ships in three flavors:
- valueOf(String s) — Accepts a String and parses it into an Integer
- valueOf(int i) — Accepts an int and parses it into an Integer
- valueOf(String s, int radix) — Accepts a String and returns an Integer representing the value and then parses it with the given base
The valueOf() method, unlike the parseInt() method, returns an Integer instead of a primitive int and also throws a NumberFormatException if the String cannot be converted properly and only accepts decimal numbers:
Running this piece of code will yield:
Integer.decode()
The decode() method accepts a single parameter and comes in one flavor:
- decode(String s) — Accepts a String and decodes it into an Integer
The decode() method accepts decimal, hexadecimal and octal numbers, but doesn’t support binary:
Running this piece of code will yield:
Conclusion
We’ve covered one of the fundamental topics of Java and common problem developers face — Converting a String to an Integer or int using tools shipped with the JDK.