Проверка на переполнение java

Переполнение и недополнение в Java

В этом руководстве мы рассмотрим переполнение и потерю значимости числовых типов данных в Java.

Мы не будем углубляться в более теоретические аспекты — мы просто сосредоточимся на том, когда это происходит в Java.

Сначала мы рассмотрим целочисленные типы данных, а затем типы данных с плавающей запятой. Для обоих мы также увидим, как мы можем определить, когда происходит переполнение или недостаточный объем.

2. Переполнение и недополнение​

Проще говоря, переполнение и потеря значимости происходят, когда мы присваиваем значение, выходящее за пределы объявленного типа данных переменной.

Если (абсолютное) значение слишком велико, мы называем это переполнением, если значение слишком мало, мы называем это недостатком.

Давайте рассмотрим пример, в котором мы пытаемся присвоить значение 10 1000 ( 1 с 1000 нулей) переменной типа int или double . Значение слишком велико для переменной типа int или double в Java, и произойдет переполнение.

В качестве второго примера предположим, что мы пытаемся присвоить значение 10-1000 (что очень близко к 0) переменной типа double . Это значение слишком мало для двойной переменной в Java, и будет потеря значимости.

Давайте посмотрим, что происходит в Java в этих случаях более подробно.

3. Целочисленные типы данных​

Целочисленные типы данных в Java: byte (8 бит), short (16 бит), int (32 бита) и long (64 бита).

Здесь мы сосредоточимся на типе данных int . То же самое относится и к другим типам данных, за исключением того, что минимальное и максимальное значения различаются.

Читайте также:  Java canvas not drawing

Целое число типа int в Java может быть отрицательным или положительным, что означает, что с его 32 битами мы можем присваивать значения от -2 31 ( -2147483648 ) до 2 31 -1 ( 2147483647 ).

Класс-оболочка Integer определяет две константы, которые содержат эти значения: Integer.MIN_VALUE и Integer.MAX_VALUE .

3.1. Пример​

Что произойдет, если мы определим переменную m типа int и попытаемся присвоить ей слишком большое значение (например, 21474836478 = MAX_VALUE + 1)?

Возможным результатом этого присвоения является то, что значение m будет неопределенным или возникнет ошибка.

Оба являются действительными результатами; однако в Java значение m будет равно -2 147 483 648 (минимальное значение). С другой стороны, если мы попытаемся присвоить значение -2147483649 ( = MIN_VALUE – 1 ), m будет равно 2147483647 (максимальное значение). Такое поведение называется целочисленным переносом.

Давайте рассмотрим следующий фрагмент кода, чтобы лучше проиллюстрировать это поведение:

 int value = Integer.MAX_VALUE-1;   for(int i = 0; i  4; i++, value++)    System.out.println(value);   > 

Мы получим следующий вывод, демонстрирующий переполнение:

Источник

Проверка на переполнение java

  • Binary representation of a given number
  • Count set bits in an integer
  • Add two bit strings
  • Turn off the rightmost set bit
  • Rotate bits of a number
  • Compute modulus division by a power-of-2-number
  • Find the Number Occurring Odd Number of Times
  • Program to find whether a given number is power of 2
  • Find position of the only set bit
  • Check for Integer Overflow
  • Find XOR of two number without using XOR operator
  • Check if two numbers are equal without using arithmetic and comparison operators
  • Detect if two integers have opposite signs
  • How to swap two numbers without using a temporary variable?
  • Russian Peasant (Multiply two numbers using bitwise operators)

Medium Problems on Bit Manipulations and Bitwise Algorithms

  • Swap bits in a given number
  • Smallest of three integers without comparison operators
  • Compute the minimum or maximum of two integers without branching
  • Smallest power of 2 greater than or equal to n
  • Program to find parity
  • Check if binary representation of a number is palindrome
  • Generate n-bit Gray Codes
  • Check if a given number is sparse or not
  • Euclid’s Algorithm when % and / operations are costly
  • Calculate square of a number without using *, / and pow()
  • Copy set bits in a range
  • Check if a number is Bleak
  • Gray to Binary and Binary to Gray conversion

Hard Problems on Bit Manipulations and Bitwise Algorithms

  • Next higher number with same number of set bits
  • Find the maximum subarray XOR in a given array
  • Find longest sequence of 1’s in binary representation with one flip
  • Closest (or Next) smaller and greater numbers with same number of set bits
  • Bitmasking and Dynamic Programming | Travelling Salesman Problem
  • Compute the parity of a number using XOR and table look-up
  • XOR Encryption by Shifting Plaintext
  • Count pairs in an array which have at least one digit common
  • Python program to convert floating to binary
  • Booth’s Multiplication Algorithm
  • Number of pairs with Pandigital Concatenation
  • Find the n-th number whose binary representation is a palindrome
  • Find the two non-repeating elements in an array of repeating elements/ Unique Numbers 2
  • Write an Interview Experience
  • Share Your Campus Experience
  • Bitwise Algorithms
  • Introduction to Bitwise Algorithms – Data Structures and Algorithms Tutorial
  • Bitwise Operators in C/C++
  • Bitwise Operators in Java
  • Python Bitwise Operators
  • JavaScript Bitwise Operators
  • All about Bit Manipulation
  • Little and Big Endian Mystery
  • Bits manipulation (Important tactics)
  • Binary representation of a given number
  • Count set bits in an integer
  • Add two bit strings
  • Turn off the rightmost set bit
  • Rotate bits of a number
  • Compute modulus division by a power-of-2-number
  • Find the Number Occurring Odd Number of Times
  • Program to find whether a given number is power of 2
  • Find position of the only set bit
  • Check for Integer Overflow
  • Find XOR of two number without using XOR operator
  • Check if two numbers are equal without using arithmetic and comparison operators
  • Detect if two integers have opposite signs
  • How to swap two numbers without using a temporary variable?
  • Russian Peasant (Multiply two numbers using bitwise operators)

Medium Problems on Bit Manipulations and Bitwise Algorithms

  • Swap bits in a given number
  • Smallest of three integers without comparison operators
  • Compute the minimum or maximum of two integers without branching
  • Smallest power of 2 greater than or equal to n
  • Program to find parity
  • Check if binary representation of a number is palindrome
  • Generate n-bit Gray Codes
  • Check if a given number is sparse or not
  • Euclid’s Algorithm when % and / operations are costly
  • Calculate square of a number without using *, / and pow()
  • Copy set bits in a range
  • Check if a number is Bleak
  • Gray to Binary and Binary to Gray conversion

Hard Problems on Bit Manipulations and Bitwise Algorithms

  • Next higher number with same number of set bits
  • Find the maximum subarray XOR in a given array
  • Find longest sequence of 1’s in binary representation with one flip
  • Closest (or Next) smaller and greater numbers with same number of set bits
  • Bitmasking and Dynamic Programming | Travelling Salesman Problem
  • Compute the parity of a number using XOR and table look-up
  • XOR Encryption by Shifting Plaintext
  • Count pairs in an array which have at least one digit common
  • Python program to convert floating to binary
  • Booth’s Multiplication Algorithm
  • Number of pairs with Pandigital Concatenation
  • Find the n-th number whose binary representation is a palindrome
  • Find the two non-repeating elements in an array of repeating elements/ Unique Numbers 2

Источник

Оцените статью