Skip to main content

Command Palette

Search for a command to run...

Number of Bit Changes to Make Two Integers Equal

Published
1 min read
Number of Bit Changes to Make Two Integers Equal
G

As a Systems Engineer at Tata Consultancy Services, I deliver exceptional software products for mobile and web platforms, using agile methodologies and robust quality maintenance. I am experienced in performance testing, automation testing, API testing, and manual testing, with various tools and technologies such as Jmeter, Azure LoadTest, Selenium, Java, OOPS, Maven, TestNG, and Postman.

I have successfully developed and executed detailed test plans, test cases, and scripts for Android and web applications, ensuring high-quality standards and user satisfaction. I have also demonstrated my proficiency in manual REST API testing with Postman, as well as in end-to-end performance and automation testing using Jmeter and selenium with Java, TestNG and Maven. Additionally, I have utilized Azure DevOps for bug tracking and issue management.

You are given two positive integers n and k.

You can choose any bit in the binary representation of n that is equal to 1 and change it to 0.

Return the number of changes needed to make n equal to k. If it is impossible, return -1.

LeetCode Problem - 3226

class Solution {
    public int minChanges(int n, int k) {
        // If n and k are already equal, no changes are needed
        if (n == k) return 0;

        // Check if all bits set in k are also set in n
        if ((n & k) == k) {
            // Calculate the result of n XOR k
            int res = (n ^ k);
            // Return the number of 1-bits in the result (number of bits that differ)
            return Integer.bitCount(res);
        }

        // If n cannot be changed to match k, return -1
        return -1;
    }
}

More from this blog

S

Software and Performance Testing Insights

462 posts

Results-Driven Agile QA Specialist | Expert in Mobile & Web Testing | Proficient in Test Planning, Execution, and Root Cause Analysis.