title: Runtime Error : Integer Overflow for Complement Number Problem
body: <p>I have 3 ways of complementing a given binary number. The 1st &amp; 3rd methods do not get any Integer Overflow Error. Can you please explain why the 2nd method gets this run time error?
  Here's the code :</p>
  
  <pre><code> int findComplement1(int num) {
          if(num==0)
              return 1;
  
          int n=num;
          int bit=1;
          while(n&gt;0)
          {
           num=num^bit;
           n/=2;
           bit=bit&lt;&lt;1;
          }
          return num;
      }
  
  //Got Integer Overflow
  int findComplement2(int num)
  {
      int n = floor(log2(num)+1);;
      int num_with_all_ones =(int) (1&lt;&lt;n)-1;
      return (num_with_all_ones^num);
  }
  
  int findComplement3(int num)
  {
      if(num==0)
          return 1;
      int result=0;
      int power=1;
      while(num&gt;0)
      {
          int pop=num%2;
          int c=(num%2)^1;
          result+=c*power;
          power=power&lt;&lt;1;
          num=num&gt;&gt;1;
      }
      return result;
  }
  </code></pre>
  
  <p><strong>This was the error message :</strong>
  Runtime Error Message: Line 7: Char 44: runtime error: signed integer overflow: -2147483648 - 1 cannot be represented in type 'int' (solution.cpp)
  SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior prog_joined.cpp:16:44</p>
  
  <p>Last executed input: 2147483647</p>