Prerequisites :
INT_MAX and INT_MIN in C/C++ and Applications.
Arithmetic shift vs Logical shift
Suppose you have a 32-bit system :
The INT_MAX would be 01111111111111111111111111111111 and INT_MIN would be 10000000000000000000000000000000. 0 & 1 in most-significant bit position representing the sign bit respectively.
Computing INT_MAX and INT_MIN In C/C++ :
The number 0 is represented as 000…000(32 times).
- We compute the NOT of 0 to get a number with 32 1s. This number is not equal to INT_MAX because the sign bit is 1, i.e. negative number.
- Now, a right shift of this number will produce 011…111 which is INT_MAX.
- INT_MIN is NOT of INT_MAX.
Note :
0 should be taken as unsigned int.
Reason :
If 0 is signed, during Step 2, right shift of 111..111 will yield 111…111. This is because arithmetic right shift preserves the sign of the number.
In Java, we have the feature of logical right shift available to us.
C++
#include <bits/stdc++.h>
using namespace std;
void printMinMaxValues()
{
unsigned int max = 0;
max = ~max;
max = max >> 1;
int min = max;
min = ~min;
cout << "INT_MAX : " << max
<< " INT_MIN : " << min;
}
int main()
{
printMinMaxValues();
return 0;
}
|
Java
public class Solution
{
static void printMinMaxValues()
{
int max = 0 ;
max = ~max;
max = max >>> 1 ;
int min = max;
min = ~max;
System.out.println( "INT_MAX " + max +
" INT_MIN " + min);
}
public static void main(String[] args)
{
printMinMaxValues();
}
}
|
Python3
def printMinMaxValues():
max = 0
max = ~ max + ( 1 << 32 )
max = max >> 1
min = max ;
min = ~ min
print ( "INT_MAX :" , max , "INT_MIN :" , min )
printMinMaxValues()
|
C#
using System;
public class GFG
{
static void printMinMaxValues()
{
uint max = 0;
max = ~max;
max = max >> 1;
int min = ( int )max;
min = ~min;
Console.WriteLine( "INT_MAX " + max +
" INT_MIN " + min);
}
public static void Main( string [] args)
{
printMinMaxValues();
}
}
|
Javascript
<script>
function printMinMaxValues()
{
let max = 0;
max = ~max;
max = max >>> 1;
let min = max;
min = ~max;
document.write( "INT_MAX - " + max +
", INT_MIN " + min);
}
printMinMaxValues();
</script>
|
Output:
INT_MAX 2147483647 INT_MIN -2147483648
Time Complexity – O(1)
Space Complexity – O(1)
Asked in : Google
If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!