NUMBER COMPLEMENTA complement of a number defined as bitwise inversion starting from highest order 1-bit change every 1 to 0 and every 0 to 1.for example n=5(decimal) = 101(binary) so the binary complement is =010(binary) = 2(decimal)Constaints : n<=0<=100000input : 50(110010)output : 13(001101)
SOURCE : NumberComplement.javastatic int getIntegerComplement(int n){ int comp = 0; int rem=0; int count =0; if (n == 1) { return 0; } else if(n == 0) { return 1; } while(n>1) { rem = n % 2; n= n / 2; if(rem==0) comp= (int) (comp+1*Math.pow(2, count)); count++; } if(n == 0) { comp= (int) (comp+1*Math.pow(2, count)); } return comp; }

0 comments :
Post a Comment