Open In App

Find numbers between two numbers such that xor of digit is k

Last Updated : 12 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given three Integers num1, num2, and k, the task is to find the count of numbers between these two numbers such that the xor of the digit is exactly k.

Examples:

Input: num1 = 100, num2 = 500, k = 3
Output: 36
Explanation: 102 113 120 131 146 157 164 175 201 210 223 232 245 254 267 276 289 298 300 311 322 333 344 355 366 377 388 399 407 416 425 434 443 452 461 470

Input: num1 = 10, num2 = 100, k = 2
Output: 7

Solving problem using linear Iteration:

  • Initialize count with 0 to count the number of digits.
  • Then, iterates through each number from num1 to num2.
  • Inside the loop, it calculates the XOR of the digits of the current number.
  • If xor = k then Increase the counter, count++.
  • Return the value of the count.

Below is the Implementation of the above approach:

C++




// C++ code for the above approach:
#include <iostream>
#include <vector>
 
using namespace std;
 
// Function to count numbers
int countNumbers(int num1, int num2, int k)
{
    int count = 0;
    for (int num = num1; num <= num2; num++) {
        int currXOR = 0;
        int temp = num;
        while (temp > 0) {
            currXOR ^= (temp % 10);
            temp /= 10;
        }
        if (currXOR == k) {
            count++;
        }
    }
    return count;
}
 
// Drivers code
int main()
{
    int num1 = 100;
    int num2 = 500;
    int k = 3;
 
    // Function Call
    int result = countNumbers(num1, num2, k);
    cout << "Count of numbers = " << result << endl;
    return 0;
}


Java




// Java code for the above approach:
import java.util.*;
 
public class GFG {
    // Function to count numbers
    public static int countNumbers(int num1, int num2,
                                   int k)
    {
        int count = 0;
        for (int num = num1; num <= num2; num++) {
            int currXOR = 0;
            int temp = num;
            while (temp > 0) {
                currXOR ^= (temp % 10);
                temp /= 10;
            }
            if (currXOR == k) {
                count++;
            }
        }
        return count;
    }
 
    // Drivers code
    public static void main(String[] args)
    {
        int num1 = 100;
        int num2 = 500;
        int k = 3;
 
        // Function Call
        int result = countNumbers(num1, num2, k);
        System.out.println("Count of numbers = " + result);
    }
}
 
// This code is contributed by Tapesh(tapeshdua420)


Python3




# Function to count numbers
def countNumbers(num1, num2, k):
    count = 0
    for num in range(num1, num2+1):
          # variable to store current xor
        currXOR = 0
        temp = num
        while temp > 0:
            currXOR ^= (temp % 10)
            temp //= 10
        if currXOR == k:
            count += 1
    return count
 
# Drivers code
num1 = 100
num2 = 500
k = 3
result = countNumbers(num1, num2, k)
print("Count of numbers =", result)


C#




using System;
 
class Program
{
    // Function to count numbers
    static int CountNumbers(int num1, int num2, int k)
    {
        int count = 0;
        for (int num = num1; num <= num2; num++)
        {
            int currXOR = 0;
            int temp = num;
            while (temp > 0)
            {
                currXOR ^= (temp % 10);
                temp /= 10;
            }
            if (currXOR == k)
            {
                count++;
            }
        }
        return count;
    }
 
    // Main method
    static void Main()
    {
        int num1 = 100;
        int num2 = 500;
        int k = 3;
 
        // Function Call
        int result = CountNumbers(num1, num2, k);
        Console.WriteLine("Count of numbers = " + result);
    }
}


Javascript




// Javascript code for the above approach:
 
// Function to count numbers
function countNumbers(num1, num2, k) {
    let count = 0;
    for (let num = num1; num <= num2; num++) {
        let currXOR = 0;
        let temp = num;
        while (temp > 0) {
            currXOR ^= (temp % 10);
            temp = Math.floor(temp / 10);
        }
        if (currXOR === k) {
            count++;
        }
    }
    return count;
}
 
// Drivers code
let num1 = 100;
let num2 = 500;
let k = 3;
 
// Function Call
let result = countNumbers(num1, num2, k);
console.log("Count of numbers = " + result);


Output

Count of numbers = 36


















Time complexity: O(N), where N is the difference.
Auxiliary Space: O(1) as constant space is used.

Solving problem Using Dynamic Programming:

In the dynamic programming approach, we use memoization to avoid redundant calculations and store the results in the dp array. By building up the solution incrementally, we can compute the count efficiently.

Steps for function: CountNumbers

  • Check if the ind is equal to the size of the digits vector. If yes, return 1 if currXOR=k, else 0
  • Check if the state for the ind, flag, and currXOR value has value. If yes, return the value.
  • Determine the limit for the current digit based on the flag and the value at the current index.
  • Initialize count=0
  • Iterate from 0 to the lower limit.
  • Update the newCurrXOR value by taking the XOR of currXOR and the digit.
  • Recursively call the countNumbers function.
  • Store the calculated count in the state, smaller flag, and currXOR value.
  • Return the count value.

Steps for function: countNumbersWithXOR

  • Convert num1 into a vector and store them in reverse order.
  • Call the countNumbers function for the digits vector, with the initial index as 0, the smaller flag as false, the initial currXOR as 0, and the target XOR k.
  • Store the count in count1.
  • Do the same for finding count2
  • Store the count in count2.
  • Return count2 – count1

Below is the Implementation of the above approach:

C++




// C++ code for the above approach:
#include <algorithm>
#include <iostream>
#include <vector>
 
using namespace std;
 
vector<vector<vector<int> > > dp;
 
int countNumbers(vector<int>& digits, int index,
                 bool smaller, int currXOR, int k)
{
    if (index == digits.size()) {
        return (currXOR == k) ? 1 : 0;
    }
    if (dp[index][smaller][currXOR] != -1) {
        return dp[index][smaller][currXOR];
    }
    int limit = (smaller || digits[index] < 1)
                    ? 9
                    : digits[index];
    int count = 0;
    for (int digit = 0; digit <= limit; digit++) {
        int newCurrXOR = currXOR ^ digit;
        count += countNumbers(
            digits, index + 1,
            smaller || (digit < digits[index]), newCurrXOR,
            k);
    }
    return dp[index][smaller][currXOR] = count;
}
 
int countNumbersWithXOR(int num1, int num2, int k)
{
    vector<int> digits;
    int temp = num1;
    while (temp > 0) {
        digits.push_back(temp % 10);
        temp /= 10;
    }
    reverse(digits.begin(), digits.end());
    dp.assign(digits.size(), vector<vector<int> >(
                                 2, vector<int>(1024, -1)));
    int count1 = countNumbers(digits, 0, false, 0, k);
 
    digits.clear();
    temp = num2;
    while (temp > 0) {
        digits.push_back(temp % 10);
        temp /= 10;
    }
    reverse(digits.begin(), digits.end());
    dp.assign(digits.size(), vector<vector<int> >(
                                 2, vector<int>(1024, -1)));
    int count2 = countNumbers(digits, 0, false, 0, k);
 
    return count2 - count1;
}
 
// C++ code for the above approach:
int main()
{
    int num1 = 100;
    int num2 = 500;
    int k = 3;
 
    // Drivers code
    int result = countNumbersWithXOR(num1, num2, k);
    cout << "Count of numbers = " << result << endl;
    return 0;
}


Java




import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
 
public class CountNumbersWithXOR {
    static int[][][] dp; // Dynamic programming array to memoize results
 
    // Function to count numbers with a specific XOR condition
    static int countNumbers(List<Integer> digits, int index, boolean smaller, int currXOR, int k) {
        if (index == digits.size()) {
            return currXOR == k ? 1 : 0;
        }
        if (dp[index][smaller ? 1 : 0][currXOR] != -1) {
            return dp[index][smaller ? 1 : 0][currXOR];
        }
        int limit = smaller || digits.get(index) < 1 ? 9 : digits.get(index);
        int count = 0;
        for (int digit = 0; digit <= limit; digit++) {
            int newCurrXOR = currXOR ^ digit;
            count += countNumbers(digits, index + 1, smaller || digit < digits.get(index), newCurrXOR, k);
        }
        dp[index][smaller ? 1 : 0][currXOR] = count;
        return count;
    }
 
    // Function to count numbers within a range that meet the XOR condition
    static int countNumbersWithXOR(int num1, int num2, int k) {
        List<Integer> digits = new ArrayList<>();
        int temp = num1;
        while (temp > 0) {
            digits.add(temp % 10);
            temp /= 10;
        }
        int n = digits.size();
        dp = new int[n][2][1024]; // Initialize the DP array
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < 2; j++) {
                Arrays.fill(dp[i][j], -1);
            }
        }
        int count1 = countNumbers(digits, 0, false, 0, k);
 
        digits.clear();
        temp = num2;
        while (temp > 0) {
            digits.add(temp % 10);
            temp /= 10;
        }
        n = digits.size();
        dp = new int[n][2][1024]; // Reset the DP array for the second number
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < 2; j++) {
                Arrays.fill(dp[i][j], -1);
            }
        }
        int count2 = countNumbers(digits, 0, false, 0, k);
 
        return count2 - count1;
    }
 
    public static void main(String[] args) {
        int num1 = 100;
        int num2 = 500;
        int k = 3;
 
        // Driver code
        int result = countNumbersWithXOR(num1, num2, k);
        System.out.println("Count of numbers = " + result);
    }
}


Python3




# Python code for the above approach
 
def countNumbers(digits, index, smaller, currXOR, k, dp):
    # Base case: reached the end of digits
    if index == len(digits):
        return 1 if currXOR == k else 0
 
    # Memoization: check if the result is already calculated
    if dp[index][smaller][currXOR] != -1:
        return dp[index][smaller][currXOR]
 
    # Determine the limit based on whether we can make the number smaller
    limit = 9 if smaller or digits[index] < 1 else digits[index]
    count = 0
 
    # Iterate through possible digits and recursively count
    for digit in range(limit + 1):
        newCurrXOR = currXOR ^ digit
        count += countNumbers(digits, index + 1, smaller or (digit < digits[index]), newCurrXOR, k, dp)
 
    # Memoize the result and return
    dp[index][smaller][currXOR] = count
    return count
 
def countNumbersWithXOR(num1, num2, k):
    # Convert numbers to lists of digits
    digits = [int(digit) for digit in str(num1)]
    # Initialize memoization table
    dp = [[[-1 for _ in range(1024)] for _ in range(2)] for _ in range(len(digits))]
    # Calculate count for the first number
    count1 = countNumbers(digits, 0, False, 0, k, dp)
 
    # Repeat the process for the second number
    digits = [int(digit) for digit in str(num2)]
    dp = [[[-1 for _ in range(1024)] for _ in range(2)] for _ in range(len(digits))]
    count2 = countNumbers(digits, 0, False, 0, k, dp)
 
    # Return the difference in counts
    return count2 - count1
 
# Driver code
num1 = 100
num2 = 500
k = 3
 
# Calculate and print the count of numbers
result = countNumbersWithXOR(num1, num2, k)
print("Count of numbers =", result)
 
# This code is contributed by Susobhan Akhuli


C#




// C# program for the above approach
using System;
using System.Collections.Generic;
 
public class GFG {
    static int[][][] dp; // Dynamic programming array to
                         // memoize results
 
    // Function to count numbers with a specific XOR
    // condition
    static int CountNumbers(List<int> digits, int index,
                            bool smaller, int currXOR,
                            int k)
    {
        if (index == digits.Count) {
            return currXOR == k ? 1 : 0;
        }
        if (dp[index][smaller ? 1 : 0][currXOR] != -1) {
            return dp[index][smaller ? 1 : 0][currXOR];
        }
        int limit = smaller || digits[index] < 1
                        ? 9
                        : digits[index];
        int count = 0;
        for (int digit = 0; digit <= limit; digit++) {
            int newCurrXOR = currXOR ^ digit;
            count += CountNumbers(
                digits, index + 1,
                smaller || digit < digits[index],
                newCurrXOR, k);
        }
        dp[index][smaller ? 1 : 0][currXOR] = count;
        return count;
    }
 
    // Function to count numbers within a range that meet
    // the XOR condition
    static int CountNumbersWithXOR(int num1, int num2,
                                   int k)
    {
        List<int> digits = new List<int>();
        int temp = num1;
        while (temp > 0) {
            digits.Add(temp % 10);
            temp /= 10;
        }
        int n = digits.Count;
        dp = new int[n][][];
        for (int i = 0; i < n; i++) {
            dp[i] = new int[2][];
            for (int j = 0; j < 2; j++) {
                dp[i][j] = new int[1024];
                for (int l = 0; l < 1024; l++) {
                    dp[i][j][l] = -1;
                }
            }
        }
        int count1 = CountNumbers(digits, 0, false, 0, k);
 
        digits.Clear();
        temp = num2;
        while (temp > 0) {
            digits.Add(temp % 10);
            temp /= 10;
        }
        n = digits.Count;
        dp = new int[n][][];
        for (int i = 0; i < n; i++) {
            dp[i] = new int[2][];
            for (int j = 0; j < 2; j++) {
                dp[i][j] = new int[1024];
                for (int l = 0; l < 1024; l++) {
                    dp[i][j][l] = -1;
                }
            }
        }
        int count2 = CountNumbers(digits, 0, false, 0, k);
 
        return count2 - count1;
    }
 
    public static void Main(string[] args)
    {
        int num1 = 100;
        int num2 = 500;
        int k = 3;
 
        // Driver code
        int result = CountNumbersWithXOR(num1, num2, k);
        Console.WriteLine("Count of numbers = " + result);
    }
}
 
// This code is contributed by Susobhan Akhuli


Javascript




// Javascript program for the above approach
 
let dp; // Dynamic programming array to memoize results
 
// Function to count numbers with a specific XOR condition
function countNumbers(digits, index, smaller, currXOR, k) {
    // Base case: if we have processed all digits
    if (index === digits.length) {
        // Check if the current XOR equals the target XOR (k)
        return currXOR === k ? 1 : 0;
    }
 
    // Check if the result for the current state is already computed
    if (dp[index][smaller ? 1 : 0][currXOR] !== -1) {
        return dp[index][smaller ? 1 : 0][currXOR];
    }
 
    // Determine the limit for the current digit based on 'smaller' flag
    const limit = smaller || digits[index] < 1 ? 9 : digits[index];
    let count = 0;
 
    // Iterate through possible digits for the current position
    for (let digit = 0; digit <= limit; digit++) {
        const newCurrXOR = currXOR ^ digit; // Update XOR with the current digit
        // Recursively count numbers for the next position
        count += countNumbers(digits, index + 1, smaller || digit < digits[index], newCurrXOR, k);
    }
 
    // Memoize the result for the current state and return
    dp[index][smaller ? 1 : 0][currXOR] = count;
    return count;
}
 
// Function to count numbers within a range that meet the XOR condition
function countNumbersWithXOR(num1, num2, k) {
    // Convert num1 to an array of digits
    let digits = [];
    let temp = num1;
    while (temp > 0) {
        digits.push(temp % 10);
        temp = Math.floor(temp / 10);
    }
    const n = digits.length;
 
    // Initialize the DP array
    dp = new Array(n)
        .fill(0)
        .map(() => new Array(2).fill(0).map(() => new Array(1024).fill(-1)));
 
    // Count numbers with XOR property for num1
    const count1 = countNumbers(digits, 0, false, 0, k);
 
    // Convert num2 to an array of digits
    digits = [];
    temp = num2;
    while (temp > 0) {
        digits.push(temp % 10);
        temp = Math.floor(temp / 10);
    }
    // Reset memoization table for num2
    dp = new Array(n)
        .fill(0)
        .map(() => new Array(2).fill(0).map(() => new Array(1024).fill(-1)));
 
    // Count numbers with XOR property for num2
    const count2 = countNumbers(digits, 0, false, 0, k);
 
    // Return the final result by subtracting counts
    return count2 - count1;
}
 
// Driver code
const num1 = 100;
const num2 = 500;
const k = 3;
 
// Main function
const result = countNumbersWithXOR(num1, num2, k);
console.log("Count of numbers =", result);
 
// This code is contributed by Susobhan Akhuli


Output

Count of numbers = 36


















Time complexity: O(10^N), where N is the number of digits in the larger of the two numbers (num1 and num2). The reason for the exponential time complexity is the recursive nature of the countNumbers function. It considers all possible combinations of digits for each position in the number, resulting in a branching factor of 10 at each level of recursion.
Auxiliary Space: O(log10(num2)). It depends on the number of digits in num2.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads