我总是记不住电话号码。我需要一个记忆规则。


当前回答

试试用Python:

>>> int('1' * 31, base=2)
2147483647

其他回答

大约是2.1 * 10^9。不需要知道确切的2^{31}- 1 = 2,147,483,647。

C

你可以在C语言中找到它:

#include <stdio.h>
#include <limits.h>

main() {
    printf("max int:\t\t%i\n", INT_MAX);
    printf("max unsigned int:\t%u\n", UINT_MAX);
}

给出(好吧,没有,)

max int:          2,147,483,647
max unsigned int: 4,294,967,295

C + 11 +

std::cout << std::numeric_limits<int>::max() << "\n";
std::cout << std::numeric_limits<unsigned int>::max() << "\n";

Java

你也可以用Java得到这个:

System.out.println(Integer.MAX_VALUE);

但是请记住,Java整数总是有符号的。

Python 2

Python有任意的精确整数。但在python2中,它们被映射为C整数。所以你可以这样做:

import sys
sys.maxint
>>> 2147483647
sys.maxint + 1
>>> 2147483648L

所以当整数大于2^31 -1时,Python会切换为long

在Objective-C (iOS和OSX)中,只需要记住这些宏:

#define INT8_MAX         127
#define INT16_MAX        32767
#define INT32_MAX        2147483647
#define INT64_MAX        9223372036854775807LL

#define UINT8_MAX         255
#define UINT16_MAX        65535
#define UINT32_MAX        4294967295U
#define UINT64_MAX        18446744073709551615ULL

最大负值(32位):-2147483648 (1 << 31)

最大正(32位)值:2147483647 ~(1 << 31)

记忆:“醉酒又好色”

drunk ========= Drinking age is 21
AK ============ AK 47
A ============= 4 (A and 4 look the same)
horny ========= internet rule 34 (if it exists, there's 18+ material of it) 

21 47 4(years) 3(years) 4(years)
21 47 48       36       48

它是231−1(32位,其中1位用于符号)。

如果你想要一个近似值,使用210 = 1024≈103,所以231≈2*109。如果您想手动计算一个精确的值,可以使用平方的求幂来得到232 = 2(25),然后除以2。你只需要平方5次就可以得到232:

2*2 = 4
4*4 = 16
16*16 = 256
256*256 = 25*25*100 + 2*250*6 + 36 = 62500 + 3000 + 36 = 65536
65536*65536 =65000*65000 + 2*65000*536 + 536*536 =  
4225000000 + 130000*536 + (250000 + 3600 + 36*36) =
4225000000 + 69680000 + 250000 + 3600 + 1296 =
4294967296

把这个除以2再减去1得到2147,483,647。如果你不需要所有的数字,只需要前三位有效数字,那么每一步平方的计算都很简单。

我在c#中做了几个天才的方法,你可以在你的生产环境中利用:

public static int GetIntMaxValueGenius1()
{
    int n = 0;
    while (++n > 0) { }
    return --n;
}

public static int GetIntMaxValueGenius2()
{
    int n = 0;
    try
    {
        while (true)
            n = checked(n + 1);
    }
    catch { }
    return n;
}