Find XOR from 1 to n Numbers - The Coding Shala

Home >> Programming >> find xor from 1 to n numbers

 In this post, we will learn how to Find XOR of 1 to n Number in Java.

Find XOR from 1 to n Numbers

Given a number n, find the xor from 1 to n.

Example:
Input: n = 6
Output: 7
Explanation: 1 ^ 2 ^ 3 ^ 4 ^ 5 ^ 6  = 7

Approach 1

Using the loop. [Simple solution]

Java Program: 

class Solution {
    
    public static void main(String[] args) {
        int n = 6;
        int result = 0;
        for(int i=1; i<=n; i++) {
            result = result ^ i;
        }
        System.out.println("XOR is: " + result);
    }
}

Approach 2 [ Efficient Method ]

Find remainder = n%4

if rem = 0, then xor will be same as n.
if rem = 1, then xor will be 1.
if rem = 2, then xor will be n+1.
if rem = 3, then xor will be 0.

Java Program: 

class Solution {
    
    public static void main(String[] args) {
        int n = 6;
        int rem = n%4;
        int result = 0;
        if(rem == 0) {
            result = n;
        } else if(rem == 1) {
            result = 1;
        } else if(rem == 2) {
            result = n+1;
        } else if(rem == 3) {
            result = 0;
        }
        System.out.println("XOR is: " + result);
    }
}


Other Posts You May Like
Please leave a comment below if you like this post or found some errors, it will help me to improve my content.

Comments

Popular Posts from this Blog

Java Program to Convert Binary to Decimal - The Coding Shala

N-th Tribonacci Number Solution - The Coding Shala

Shell Script to Create a Simple Calculator - The Coding Shala

Introduction to Kotlin Programming Language for Backend Development - The Coding Shala

Java Program to Reverse a String using Stack - The Coding Shala