XOR of 1 to n Numbers

Easy Bit Manipulation Tricks to remember Original on GeeksforGeeks

XOR of 1 to n Numbers is a easy bit manipulation problem solved with the tricks to remember pattern. The best approach, optimal (period-4 pattern), runs in O(1) time and O(1) space. Below are 2 approaches in Java, from loop up.

Problem

Return 1 ^ 2 ^ 3 ^ ... ^ n (XOR of all numbers from 1 to n) in O(1).

Examples

Example 1

Input
n = 6
Output
7
Why
1^2^3^4^5^6 = 7.

Example 2

Input
n = 7
Output
0

Constraints

  • 1 <= n <= 10^9

Animated walkthrough

A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

Solutions

Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the Java code.

ApproachTimeSpace
LoopO(n)O(1)
Optimal (period-4 pattern)O(1)O(1)

1Loop

TimeO(n)
SpaceO(1)

XOR every number from 1 to n.

  1. x = 0; for i in 1..n: x ^= i.
Java
class Solution {
    static int xorUpto(int n) {
        int x = 0;
        for (int i = 1; i <= n; i++) x ^= i;
        return x;
    }
}

2Optimal (period-4 pattern)

TimeO(1)
SpaceO(1)

Every block of four consecutive numbers starting at a multiple of 4 XORs to 0, so the answer depends only on n % 4: 0 → n, 1 → 1, 2 → n + 1, 3 → 0.

  1. switch (n % 4).
Java
class Solution {
    static int xorUpto(int n) {
        switch (n % 4) {
            case 0: return n;
            case 1: return 1;
            case 2: return n + 1;
            default: return 0;
        }
    }
}

Edge cases to test

  • n = 1

Hints

Hint 1

Write out the prefix XORs for n = 1..8. They repeat every 4: n, 1, n + 1, 0.

FAQ

What is the best time complexity for XOR of 1 to n Numbers?

Optimal (period-4 pattern) runs in O(1) time and O(1) extra space.

Which pattern does XOR of 1 to n Numbers use?

It is a bit manipulation problem that uses the tricks to remember pattern. Other problems with the same pattern: Number of 1 Bits, Set the rightmost unset bit.

Is there a brute force solution for XOR of 1 to n Numbers?

Yes. Loop takes O(n) time and O(1) space. XOR every number from 1 to n.

Which edge cases should I test for XOR of 1 to n Numbers?

n = 1.