📜  [0, N] 范围内的整数 K 的计数,使得 (K XOR K+1) 等于 (K+2 XOR K+3)

📅  最后修改于: 2022-05-13 01:56:05.237000             🧑  作者: Mango

[0, N] 范围内的整数 K 的计数,使得 (K XOR K+1) 等于 (K+2 XOR K+3)

给定一个整数N ,任务是打印所有小于或等于N的非负整数K的计数,使得KK+1的按位异或等于K+2K+3的按位异或。

例子:

朴素方法:最简单的方法是在范围[0, N]上进行迭代并检查当前数字是否满足条件。如果满足,则将计数增加1 。检查所有数字后,打印计数值。

时间复杂度: O(N)
辅助空间: O(1)

有效方法:上述方法可以通过观察[0, N]范围内的所有偶数满足给定条件来优化。

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to count all the integers
// less than N satisfying the given
// condition
int countXor(int N)
{
 
    // Store the count of even
    // numbers less than N+1
    int cnt = N / 2 + 1;
 
    // Return the count
    return cnt;
}
 
// Driver Code
int main()
{
    // Given Input
    int N = 4;
 
    // Function Call
    cout << countXor(N);
 
    return 0;
}


Java
// Java Program for the above approach
import java.io.*;
 
class GFG
{
   
    // Function to count all the integers
    // less than N satisfying the given
    // condition
    static int countXor(int N)
    {
 
        // Store the count of even
        // numbers less than N+1
        int cnt = (int) N / 2 + 1;
 
        // Return the count
        return cnt;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
 
        // Given Input
        int N = 4;
 
        // Function Call
        System.out.println(countXor(N));
 
    }
}
 
// This code is contributed by Potta Lokesh


Python3
# Python 3 program for the above approach
 
# Function to count all the integers
# less than N satisfying the given
# condition
def countXor(N):
   
    # Store the count of even
    # numbers less than N+1
    cnt = N // 2 + 1
 
    # Return the count
    return cnt
 
# Driver Code
if __name__ == '__main__':
   
    # Given Input
    N = 4
 
    # Function Call
    print(countXor(N))
     
    # This code is contributed by SUTENDRA_GANGWAR.


C#
// C# program for the above approach
using System;
 
class GFG{
     
// Function to count all the integers
// less than N satisfying the given
// condition
static int countXor(int N)
{
     
    // Store the count of even
    // numbers less than N+1
    int cnt = (int)N / 2 + 1;
 
    // Return the count
    return cnt;
}
 
// Driver code
static void Main()
{
     
    // Given Input
    int N = 4;
 
    // Function Call
    Console.WriteLine(countXor(N));
}
}
 
// This code is contributed by abhinavjain194


Javascript


输出
3

时间复杂度: O(1)
辅助空间: O(1)