File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Fast way to count ~X where X is any number (even -ve) Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Fast way to count ~X where X is any number (even -ve)" Watch "Fast way to count ~X where X is any number (even -ve)" New topic

Fast way to count ~X where X is any number (even -ve)

kishor kotecha

Joined: Oct 02, 2000
Posts: 27
I was facing a problem in converting not of a number i.e. ~X.
Though I know the method ...
1. find the binary of the number and
2. revese all the bits.
It can be done but is a SLOW process when you are short of time in exam. for eg. what is ~4569? It will take time. find binary of 4569 will take time manually in exam. I found a VERY FAST method somewhere on net.
fast method ~x = -x -1
i.e. ~4569 = -4569 -1 = -4570.
or ~-1234 = --1234 -1 = 1233.
simple isnt it?
I thought this might be usefule to many in exam and hence posted on saloon. Suggestions welcome.
Sathvathsan Sampath
Ranch Hand

Joined: Oct 03, 2000
Posts: 96
The reasoning behind this formula is as follows:
1) Complement of a number is basically inverting the bits i.e. 0 ->1 and vice versa.
So, when we put a '-' sign in front of a no, then internally, this is calculated in 2s complement form:- first invert the bits (i.e. 1's complement) and then add 1 to this complemented number.
2) Since, we are just intrested in the inverted bits, subtracting 1 from the above inverted number will st away give the 1s complement form of the original no.
In short,
for -2:
2 -> 0010
-2 -> in 2s complement is: 1's complement + 1 i.e
1s complement of 2 = ivert bits of 0010 = 1101
now adding 1 gives: 1110 which is the 2s complement form of -2
Hence, doing exactly the opposite of last step would give as the desired quick answer for getting ~2.

- Sathvathsan Sampath
I agree. Here's the link:
subject: Fast way to count ~X where X is any number (even -ve)
It's not a secret anymore!