• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

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

 
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
Ranch Hand
Posts: 96
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.

 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic