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.
Loading...
  • Practice
  • Compete
  • Jobs
  • Leaderboard
  1. Practice
  2. Algorithms
  3. Bit Manipulation
  4. Flipping bits
  5. Discussions

Flipping bits

  • Problem
  • Submissions
  • Leaderboard
  • Discussions
  • Editorial
  • Topics

Sort 316 Discussions, By:

votes
  • recency
  • votes

Please Login in order to post a comment

  • bcrawford 4 years ago+ 3 comments

    Forgive me if I am mistaken, but the discussion board should be for discussion of the problems not for users to randomly post their solutions...

    20|
    Permalink
    • mjk 4 years ago+ 3 comments

      You'd be surprised to learn that there can be different solutions to the same problem.

      For example, in 'Lonely Integers', I had a solution that worked. But then I saw there was a much more simpler answer that would run faster and I learned something new. :)

      118|
      ParentPermalink
      • niuworld 4 years ago+ 0 comments

        Exactly

        1|
        ParentPermalink
      • AllisonP 4 years ago+ 1 comment

        Totally agree, and I'd like to add that links to full submissions will not display for users who have not yet submitted a solution to the problem.

        14|
        ParentPermalink
        • wittrup 2 years ago+ 1 comment

          How about a page that automatically picks a selection of the successful submissions? For each language, with one criteria as the shortest amount of code, another criteria being the fastest code, another one-liners etc. So that when you have submitted solutions to the problem, and are really stuck and just want to look at answers you can buy you into a page showing all that.

          11|
          ParentPermalink
          • 7andrexu7 1 year ago+ 0 comments

            codeforces shows the size utilized by your algorithm and time elapsed.....You can filter the languages too

            1|
            ParentPermalink
      • dyesdyes 2 years ago+ 2 comments

        That is why there is an editorial (now, not sure about 2 years ago though)

        -1|
        ParentPermalink
        • AnonymousNovice 2 years ago+ 0 comments

          sometimes other users provide good and much smarter solution then editorial.

          6|
          ParentPermalink
        • Kanudo_10 8 months ago+ 0 comments
          [deleted]
          -2|
          ParentPermalink
    • JKDos 2 years ago+ 0 comments

      Sharing source code is great. Not only will you learn new ways, or even teach new ways. You also will get the lightbulb turned on.



      Sometimes, the chanllenges are worded in a way that you can't understand what's being ask, or maybe you just have no clue. Coming to to discussion board, if you happen to find a solution, you can read it through and understand what's being done. AND BOOM the lightbulb comes on. Then rewrite it to your own language.


      Doing so, you've just learned something new. Either way.

      13|
      ParentPermalink
    • AnonymousNovice 2 years ago+ 0 comments

      Solution is posted for review. Somebody can suggest some improvement also.

      0|
      ParentPermalink
  • sussmansa 4 years ago+ 2 comments

    Ohh wow, just figured it out. The first number is the number of inputs. So the example is 3 values, value1, value2, value3. The description is just bad.

    16|
    Permalink
    • kreon 4 years ago+ 1 comment

      Plus, you need to ignore the specified constraints of 1 T 100

      0|
      ParentPermalink
      • sussmansa 4 years ago+ 0 comments

        It has been fixed, T is the number of values below the first line and 1 < T < 100.

        1|
        ParentPermalink
    • gracelovesrmit 1 year ago+ 0 comments

      wow.....that makes sense....

      -1|
      ParentPermalink
  • XeroOl 4 years ago+ 4 comments

    java doesn't do unsigned integers, this was a pain

    14|
    Permalink
    • anaspk 4 years ago+ 6 comments

      Exactly!! After wasting some 15-20 minutes in Java, I switched to C++ and it was done in 1 minute :(

      13|
      ParentPermalink
      • ak278anand 4 years ago+ 8 comments

        Simple solution in java

        private static long complement(long num){
        
            return maxInt - num;
        
        }
        

        Where long maxInt=(long)Math.pow(2, 32)-1;

        34|
        ParentPermalink
        • guilhebl 4 years ago+ 1 comment

          or long maxInt = Integer.MAX_VALUE;

          1|
          ParentPermalink
          • ststhh 3 years ago+ 1 comment

            Integer.MAX_VALUE == Math.pow(2, 31)-1 and we need Math.pow(2, 32)-1

            9|
            ParentPermalink
            • csmattjohnston 2 years ago+ 1 comment

              Why is it Math.pow(2, 32)-1 instead of Math.pow(2, 31)-1?

              0|
              ParentPermalink
              • bcwfs 2 years ago+ 0 comments

                It's the difference between signed and unsigned numbers. Signed numbers take one bit to save the -/+ state and thus the max number would be something like 0111...1 (since the first bit is usually the sign bit) not 1111...1

                1|
                ParentPermalink
        • giyer 4 years ago+ 1 comment

          Why does that work? I'm not sure I understand.

          1|
          ParentPermalink
          • AllisonP 3 years ago+ 1 comment

            If maxInt is the maximum value an integer can have, subtracting the original number will give you the complement. For example: If the input number is 6, that's 110 (00000110) in binary. 11111111 - 00000110 = 11111001, which, as you can see, is the input value's flipped bits.

            45|
            ParentPermalink
            • csmattjohnston 2 years ago+ 0 comments

              Thank you for explaining!

              0|
              ParentPermalink
        • pankaj113 3 years ago+ 2 comments

          Solution passes two of the nine test cases

          0|
          ParentPermalink
          • osoriomar 3 years ago+ 0 comments

            Are you using a bit mask to solve the problem?

            3|
            ParentPermalink
          • ishtiaque_h 3 years ago+ 1 comment

            Happned to me, too. Later had to buy input-output to realize that the problem statement says input could be 2^32. That you cannot fit into an integer. Try reading the input as long. That worked for me. Thanks.

            1|
            ParentPermalink
            • saif01md 2 years ago+ 0 comments

              but long is also 4 bits...we have to use unsigned long same as unsignned int ? pleasr help

              0|
              ParentPermalink
        • bnegrao 3 years ago+ 1 comment

          Why does the integers must be declared as "long"? why can't them just be 'int'? isn't int supposed to represent 32 bits number? ...

          0|
          ParentPermalink
          • ajboss 3 years ago+ 0 comments

            int ranges from −2,147,483,648 to 2,147,483,647

            unsigned int ranges from 0 to 4,294,967,295

            the size is same but its the values that change!

            simply read it as signed int and unsigned int. you'll get an idea.

            2|
            ParentPermalink
        • Leonina 3 years ago+ 4 comments

          Or if you want to do it with bitwise operators in java:

          long num = in.nextLong();

          long maxValue = Math.pow(2,32)-1;

          System.out.println(num ^ maxValue);

          8|
          ParentPermalink
          • abhi_net5202088 2 years ago+ 0 comments

            cool. just few lines solution.

            0|
            ParentPermalink
          • vincent_g 2 years ago+ 0 comments

            Great idea, that num ^ maxValue.

            0|
            ParentPermalink
          • Aktan 2 years ago+ 0 comments

            Or, you could do num ^ 0xFFFFFFFFL instead!

            3|
            ParentPermalink
          • Sarthak10 1 year ago+ 0 comments

            Math.pow() returns a 'double' value,so you need to typecast it to 'long' before putting it into maxValue.

            1|
            ParentPermalink
        • kevin_lin790 2 years ago+ 0 comments

          So clever. Would +20 it if I could.

          (I made a solution in Python using bit operations, come to find out I never needed it.)

          0|
          ParentPermalink
        • lonewolff 1 year ago+ 0 comments

          i did the same thing but in a twisted way. Yours was much simpler

          return ~n<0?(long)Math.pow(2,32)+~n:~n;
          
          -1|
          ParentPermalink
        • sushmabiswas7 2 months ago+ 0 comments

          Thanks very much for this!

          My initial implementation was timing out - too crude :/

          This is MUCH better:

          def flippingBits(n): flipped_n=(pow(2,32)-1)-n return flipped_n

          0|
          ParentPermalink
      • A_N_P 4 years ago+ 0 comments

        thats true

        0|
        ParentPermalink
      • javierchacana 4 years ago+ 0 comments

        Same here :(

        0|
        ParentPermalink
      • emaskovsky 4 years ago+ 5 comments

        Yes indeed, the solutions in other languages seem pretty crazy.

        In C++, I just do

        unsigned x;
        cin >> x;
        cout << ~x << endl;
        

        Done :D

        18|
        ParentPermalink
        • MistaTwist 4 years ago+ 1 comment

          I tried this initially in JavaScript, and instantly failed. Good place for me to start, though, I guess!

          0|
          ParentPermalink
          • Kevinagin 2 years ago+ 1 comment

            To do this in JavaScript, you need to end your operation with a Zero-fill right shift (>>>) so the result will be treated as an unsigned integer.

            Not quite as straight-foward, but it should still be only be one line of code: ~n >>> 0.

            1|
            ParentPermalink
            • darkjedi 1 year ago+ 0 comments

              I didn't understand >>> until now. You are a star :+1:

              0|
              ParentPermalink
        • sahildhawan22 3 years ago+ 2 comments

          That's what I thought but I used int x, instead of unsigned. Can you explain why it didn't worked?

          0|
          ParentPermalink
          • emaskovsky 3 years ago+ 1 comment

            Depends how you print it. The bits are likely correct, buut the interpretation of int in cout is indeed different than interpretation of unsigned.

            I.e. with int, you'd need to cast it to unsigned just for the printing, for example:

            int x;
            ...
            cout << static_cast<unsigned>(~x) << endl;

            (and indeed if there is some number in the input which is greater than the max signed int, i.e. 2147483647, it will not work as well because of that - and such numbers are a valid input according to the description)

            1|
            ParentPermalink
            • sahildhawan22 3 years ago+ 0 comments

              But doing other bit manipulation questions, I have seen it correctly resembles the decimal value. Here for 5 (101), it should print 2 (010), but output I get is -1.

              0|
              ParentPermalink
          • maximshen 3 years ago+ 0 comments

            This at least shows how C++ is more handy than Java

            0|
            ParentPermalink
        • osoriomar 3 years ago+ 2 comments

          That looks pretty straightforward!

          What is the name of the "~" expression? Reverse? Inverse?

          0|
          ParentPermalink
          • osoriomar 3 years ago+ 0 comments

            I just added a bitmask for the largest 32 bits possible number and apply XOR to get the new number. It's not very elegant but it worked.

                    string current = Console.ReadLine();
                    Console.WriteLine(4294967295^long.Parse(current));
            
            1|
            ParentPermalink
          • crystalgong123 3 years ago+ 0 comments

            "~" (tilde) is the bitwise NOT operator.

            0|
            ParentPermalink
        • harshitagarwal37 3 years ago+ 1 comment

          does ~ also changes the sign of the number ??

          0|
          ParentPermalink
          • mgperson 3 years ago+ 1 comment

            It does if you're using a normal (signed) int. One bit is reserved for the sign and since you're flipping each bit you by definition are flipping the sign bit.

            0|
            ParentPermalink
            • harshitagarwal37 3 years ago+ 1 comment

              which bit stands for sign change ?

              0|
              ParentPermalink
              • mgperson 3 years ago+ 0 comments

                The sign bit is always the most significant bit in the bit representation of the number. Generally the convention is to write the MSB as the leftmost, but this isn't always the case: https://en.wikipedia.org/wiki/Most_significant_bit For example, the 8 bit number 10001001 = -9. The leftmost 1 indicates a negative number.

                0|
                ParentPermalink
        • abhilash_challa 2 years ago+ 0 comments

          why doesnt the same work in C ?

          0|
          ParentPermalink
      • AllisonP 4 years ago+ 1 comment

        I completed it in Java by using longs and complement addition.

        ~n + 0x0000000100000000L
        
        1|
        ParentPermalink
        • heerokenshin 3 years ago+ 0 comments

          that was very slick of your part! cheers!

          1|
          ParentPermalink
      • mitrandir 5 months ago+ 0 comments

        After reading this i switched to go and was ready under 1 minutes as well :) Thank you anaspk !

        return int64(uint32(n)^(^uint32(0)))

        0|
        ParentPermalink
    • tainingw 4 years ago+ 0 comments
      [deleted]
      0|
      ParentPermalink
    • xiaohanyu 4 years ago+ 0 comments

      Java 8 has a new Integer/parseUnsignedInt function, check http://docs.oracle.com/javase/8/docs/api/java/lang/Integer.html#parseUnsignedInt-java.lang.String-

      0|
      ParentPermalink
    • rajmalhotra91195 3 years ago+ 0 comments

      You can use long,no problem I had done it using long.

      0|
      ParentPermalink
  • Soumyadeep_B 4 years ago+ 3 comments

    1 XOR anything gives its inverse. Hence, for 32 bit unsigned numbers , (2^32 -1) XOR 'the given number' flips each bit. I guess its possibly the fastest way to get this done.

    8|
    Permalink
    • subho_mukherjee 4 years ago+ 0 comments

      100 %

      0|
      ParentPermalink
    • scarpenter 4 years ago+ 0 comments

      Faster then simply using the ~ (one's complement) operator? I guess I thought maybe the compiler optimized a action so it wouldn't matter.

      3|
      ParentPermalink
    • charvakcpatel007 3 years ago+ 1 comment

      return ~x;

      3|
      ParentPermalink
      • Dim_S 3 years ago+ 2 comments

        You're right but some programming languages have no unsigned int or long, e.g. Python. In this case XOR is the best solution.

        2|
        ParentPermalink
        • Jfreegman 3 years ago+ 0 comments

          Or just add 2^32 to the one's complement result:

          return (~x) + (1<<32)

          1|
          ParentPermalink
        • vincent_g 2 years ago+ 0 comments

          or Java :(

          0|
          ParentPermalink
  • shrikanthmethre1 4 years ago+ 1 comment

    kindly give the description properly

    5|
    Permalink
    • s1w2 4 years ago+ 1 comment

      first you can take value from user and there is 3 point which you have to take care.... 1-input should convert into binary 2-binary value have to flipp means where 1 put 0 and where 0 put 1 3-You got flipped number now again you have to convrt it into decimal ,the ligic are... for (int i = arr.Length - 1; i >= 0; i--) {

                      uint x = arr[i];
                      uint r = x;
                      if (x == 1)
                      {
                          value = Convert.ToUInt32(Math.Pow(2, i));
                          val += value;
      
                      }
                      else
                      {
                          if (r == 0)
                          {
      
                          }
                          else
                          {
                              value = Convert.ToUInt32(Math.Pow(0, i));
                              val += value;
                          }
      
                      }
      
      
                  }
      

      this is in c# program ....you can do it in c and c++ Thank You Swatantra Mishra

      0|
      ParentPermalink
      • ektajaiswal3mar 3 years ago+ 1 comment

        Can be done using NOT gate

        int T;
        cin >> T;
        unsigned int *n = new unsigned int[T];
        for(int i = 0; i<T; i++)
            {
            cin >> n[i];
        }
         for(int i = 0; i<T; i++)
             {
             cout << ~n[i] << "\n";
         }
        
        -1|
        ParentPermalink
        • keyurhariya 2 years ago+ 0 comments

          This solutions works fine but using for loops adds a lot of processor cycles. Also, no need to store all the numbers from input, you can save memory by processing one test case at a time. Alternative to same solution but speed and memory efficient:

          int T;
          unsigned int n;
          cin >> T;
          
          while(T--){
              cin >> n;
              cout << ~n << endl;
          }
          
          0|
          ParentPermalink
  • arun_morampudi 3 years ago+ 0 comments

    just noticed.,its a single line code as the output we seek is the difference b/w (2^32)-input_n. This aint worth 40 points :P

    4|
    Permalink
  • akeim 3 years ago+ 0 comments

    Simple solution in javascript after shifting the first item off the array

    return(~integer >>> 0)
    

    Basically it shifts the inverted array to the right, and inputs zero as the sign bit, making the result the equivalent of an unsigned int in other languages.

    4|
    Permalink
  • abhishek106 2 years ago+ 4 comments
    n = int(input())
    
    for _ in range(n):
        val = int(input())
        print(val^4294967295)
    
    3|
    Permalink
    • kalez 2 years ago+ 0 comments

      nice,

      0|
      ParentPermalink
    • KL30246 3 weeks ago+ 0 comments

      Can u explain me how this works bro? i mean... how did u get that idea!!?

      0|
      ParentPermalink
    • the_dhrubo 3 weeks ago+ 0 comments

      just do it :

      return n ^ 4294967295

      0|
      ParentPermalink
    • dm_dubovitsky 2 days ago+ 0 comments

      Easy to replace last line for:

      print(val^0xffffffff)

      0|
      ParentPermalink
  • mayank7577 5 months ago+ 0 comments

    here is my code of in O(1)-

    long flippingBits(long n) {
        
        long res = n^(0xffffffff);
        return res ;
    }
    
    2|
    Permalink
  • jairamg 4 years ago+ 2 comments

    Hi all, I am getting a 'runtime error' after code submission. I am pretty sure it is not a timing issue. Any idea why this is the case?

    2|
    Permalink
    • [deleted] 4 years ago+ 1 comment

      Same, my solution is correct too, as I've tested it. Submited using java

      0|
      ParentPermalink
      • dheerajHackerRank Admin 4 years ago+ 1 comment

        @DanHu,

        You can download the failing testcase and test the code in your local machine or paste it in the custom testcase window to debug your code. a video explaining the same is given here

        0|
        ParentPermalink
        • [deleted] 4 years ago+ 0 comments

          When I test the cases on my machine, it works correctly. Its only when I I am submitting it that I get runtime errors

          0|
          ParentPermalink
    • dheerajHackerRank Admin 4 years ago+ 1 comment

      @jairam, Looks like you solved the challenge. Congrats!!

      0|
      ParentPermalink
      • rkbansal83 4 years ago+ 0 comments

        I am also getting runtime error after code submission. It works fine on my local. Submitted using java

        1|
        ParentPermalink
Load more conversations

Need Help?


View editorial
View top submissions
  • Contest Calendar
  • Blog
  • Scoring
  • Environment
  • FAQ
  • About Us
  • Support
  • Careers
  • Terms Of Service
  • Privacy Policy
  • Request a Feature