Tip

1. Leap Year

判断闰年 两种情况是闰年.

  • 能被400整除,

  • 能被4整除且不能被100整除,如1900

    y % 4 == 0 and y % 100 != 0 or y % 400 == 0

    return (y%100 != 0 && y%4 == 0) || (y%400 == 0)

    # and precedence is higher than or,
    # and expression will execute first, then the result will calculate with or

2. float number equal

判断两个浮点数a和b是否相等时,不要用a==b, 用fabs(a-b) < 1e-9.

3. int to be Odd or Even

  • 判断一个整数是否为奇数,x % 2 != 0, 不要用x % 2 == 1
check the last digit to be 1 or not.
if (num & 0x1) = true, 奇数
else 偶数

4. Median of size n array

n is odd:middle element

n is even: average of middle two elements.

5. Max or Min int

  • in C++ : INT_MAX INT_MIN
  • in Python3:
import sys
maximum = sys.maxsize
minimum = -sys.maxsize - 1

6. Convert char to int

char a = '4';
int ia = a - '0';

results matching ""

    No results matching ""