🔢 Integer Tricks

Math Functions

abs, min, max, pow, sqrt — and overflow-safe integer limits

These show up in almost every interview problem: clamping values, checking distances, avoiding overflow. Know your language's integer limits — Java's Integer.MAX_VALUE is the go-to sentinel.

Language:
Python
Loading...

All languages — abs / min / max / pow / sqrt

JavaScript
console.log(Math.abs(-7));       // 7
console.log(Math.min(3, 5));     // 3
console.log(Math.max(3, 5));     // 5
console.log(Math.min(...[3,1,4,1,5])); // 1
console.log(Math.max(...[3,1,4,1,5])); // 5

console.log(Math.pow(2, 10));    // 1024
console.log(2 ** 10);            // 1024 (ES2016)
console.log(Math.sqrt(16));      // 4
console.log(Math.floor(Math.sqrt(16))); // 4

// Infinity
console.log(Infinity > 1e9);    // true
console.log(Number.MAX_SAFE_INTEGER); // 9007199254740991
TypeScript
console.log(Math.abs(-7));
console.log(Math.min(3, 5));
console.log(Math.max(3, 5));
console.log(Math.pow(2, 10));  // 1024
console.log(Math.sqrt(16));    // 4
console.log(Math.floor(Math.sqrt(16))); // 4

const INF = Infinity;
const NEG_INF = -Infinity;
Java
// Java: Math class + integer limits
System.out.println(Math.abs(-7));       // 7
System.out.println(Math.min(3, 5));     // 3
System.out.println(Math.max(3, 5));     // 5

System.out.println(Math.pow(2, 10));    // 1024.0 (double!)
System.out.println((int) Math.pow(2, 10)); // 1024

System.out.println(Math.sqrt(16));      // 4.0
System.out.println((int) Math.sqrt(16)); // 4

// Integer limits — use as sentinels
int INF = Integer.MAX_VALUE; // 2_147_483_647
int NEG_INF = Integer.MIN_VALUE; // -2_147_483_648

// Watch out: INF + 1 overflows to MIN_VALUE!
// Use Long when values can exceed 2^31
long big = Long.MAX_VALUE;
Go
package main
import (
    "fmt"
    "math"
)

func main() {
    fmt.Println(math.Abs(-7))    // 7
    fmt.Println(math.Min(3, 5))  // 3 (float64!)
    fmt.Println(math.Max(3, 5))  // 5 (float64!)

    // For ints, write your own or use if
    a, b := 3, 5
    if a < b { fmt.Println(a) } // min for ints

    fmt.Println(math.Pow(2, 10))  // 1024
    fmt.Println(math.Sqrt(16))    // 4
    fmt.Println(int(math.Sqrt(16))) // 4

    const INF = math.MaxInt
    fmt.Println(INF)
}
C++
#include <iostream>
#include <cmath>
#include <algorithm>
#include <climits>
using namespace std;

int main() {
    cout << abs(-7) << endl;        // 7
    cout << min(3, 5) << endl;      // 3
    cout << max(3, 5) << endl;      // 5

    cout << pow(2, 10) << endl;     // 1024 (double)
    cout << (int)pow(2, 10) << endl; // 1024
    cout << sqrt(16) << endl;       // 4
    cout << (int)sqrt(16) << endl;  // 4

    // Integer limits
    cout << INT_MAX << endl;   // 2147483647
    cout << INT_MIN << endl;   // -2147483648
    cout << LLONG_MAX << endl; // for long long

    // STL min/max on arrays
    int arr[] = {3, 1, 4, 1, 5};
    cout << *min_element(arr, arr+5) << endl; // 1
    cout << *max_element(arr, arr+5) << endl; // 5
}