本文共 678 字,大约阅读时间需要 2 分钟。
Write a program to add one to a given number. You are not allowed to use operators like ‘+’, ‘-’, ‘*’, ‘/’, ‘++’, ‘–’ …etc.
Examples:
Input: 12 Output: 13Input: 6
Output: 7
We know that the negative number is represented in 2′s complement form on most of the architectures. We have the following lemma hold for 2′s complement representation of signed numbers.
Say, x is numerical value of a number, then
~x = -(x+1) [ ~ is for bitwise complement ]
(x + 1) is due to addition of 1 in 2′s complement conversion
To get (x + 1) apply negation once again. So, the final expression becomes (-(~x)).
int addOne(int x){ return (-(~x));}
转载地址:http://hexti.baihongyu.com/