先决条件: C/C++和应用程序中的INT_MAX和INT_MIN。 算术移位与逻辑移位 假设您有一个32位系统: INT_MAX将是 01111111111111111111111111111111 而INT_MIN将是 10000000000000000000000000000000 .0和1分别代表符号位的最高有效位位置。 在C/C++中计算INT_MAX和INT_MIN: 数字0表示为 000…000 (32次)。
null
- 我们计算 不 0的值,得到一个32 1的数字。该数字不等于INT_MAX,因为符号位为1,即负数。
- 现在,这个数字的右移将产生 011…111 这就是INT_MAX。
- INT_MIN不属于INT_MAX。
注: 0应被视为无符号整数。 原因: 如果0是有符号的,则在第2步中,将111右移。。111将产生111…111。这是因为算术右移保留了数字的符号。 在Java中,我们可以使用逻辑右移功能。
C++
// CPP code to compute INT_MAX and INT_MIN using // bitwise operations #include <bits/stdc++.h> using namespace std; void printMinMaxValues() { // 0 saved as unsigned int unsigned int max = 0; // Computing NOT of 0 max = ~max; // 1 time arithmetic right shift max = max >> 1; // Computing INT_MIN int min = max; // INT_MIN = ~INT_MAX min = ~min; // Printing the result cout << "INT_MAX : " << max << " INT_MIN : " << min; } // Driver code int main() { printMinMaxValues(); return 0; } |
JAVA
// Java code to compute INT_MAX and INT_MIN using // bitwise operations public class Solution { static void printMinMaxValues() { int max = 0 ; // Computing NOT of 0 max = ~max; // 1 time logical right shift for INT_MAX max = max >>> 1 ; // Computing INT_MIN int min = max; // INT_MIN = ~INT_MAX min = ~max; // Printing the result System.out.println( "INT_MAX " + max + " INT_MIN " + min); } public static void main(String[] args) { printMinMaxValues(); } } |
Javascript
<script> // Javascript code to compute INT_MAX and INT_MIN using // bitwise operations function printMinMaxValues() { let max = 0; // Computing NOT of 0 max = ~max; // 1 time logical right shift for INT_MAX max = max >>> 1; // Computing INT_MIN let min = max; // INT_MIN = ~INT_MAX min = ~max; // Printing the result document.write( "INT_MAX - " + max + ", INT_MIN " + min); } // driver program printMinMaxValues(); // This code is contributed by code_hunt. </script> |
输出:
INT_MAX 2147483647 INT_MIN -2147483648
被问到: 谷歌 本文由 罗希特·塔普里亚尔 .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 写极客。组织 或者把你的文章寄到contribute@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。 如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END