We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
  • Hackerrank Home
  • Prepare
    NEW
  • Certify
  • Compete
  • Career Fair
  • Hiring developers?
  1. Prepare
  2. Tutorials
  3. 30 Days of Code
  4. Day 29: Bitwise AND
  5. Discussions

Day 29: Bitwise AND

Problem
Submissions
Leaderboard
Discussions
Editorial
Tutorial

    You are viewing a single comment's thread. Return to all comments →

  • saiyanPride
    6 years ago+ 3 comments

    Instead of having to test various combinations of A & B, once can simply determine the result with knowledge of the value of the last digit of k.

    Thought Process: Always strive to see if k-1 can be achieved, if not then try k-2 and so on. This is because the maximum value less than k is k-1, but (k-1) will only be valid if it can be formed via A&B

    Here it goes:

    (I) If k ends with 1, then the result is (k-1) In this case k-1 can always be formed by switching off the last digit of k, where k is .......1

    (II) If k ends with 0, and is of form 2^m i.e. a power of 2 then result is (k-1) or (k-2). Let k=2^m If (2^{m+1})-1 is in the range, then result is (k-1). In this case B=(2^{m+1})-1 and A=k-1

    else, result is (k-2). (k-2) is always guaranteed as it is the precursor of a binary number that ends with a 1, see (I)

    (III) The last possible case is where k ends with 0, and is not a power of 2. Again the result is either (k-1) or (k-2)

    If the number obtained by switching on the rightmost 0 of (k-1) is the range, then that number can be bitwise multiplied by k-1 to give (k-1). Otherwise result is (k-2). (k-2) is always guaranteed as it is the precursor of a binary number that ends with a 1, see (I) & (II)

    see code: https://github.com/niranfor1/superQuantHackerrank/blob/master/30DaysOfCodeBitwiseAND.cpp

    36|
    Permalink
  • Blog
  • Scoring
  • Environment
  • FAQ
  • About Us
  • Support
  • Careers
  • Terms Of Service
  • Privacy Policy
  • Request a Feature