本文主要是介绍Add 1 to a given number,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
reference:
http://www.geeksforgeeks.org/add-1-to-a-given-number/
Problem Definition:
Write a program to add one to a given number. You are not allowed to use operators like ‘+’, ‘-’, ‘*’, ‘/’, ‘++’, ‘–’ …etc.
Examples:
Input: 12
Output: 13
Input: 6
Output: 7
Solution:
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)).
Code:
int addOne(int x)
{return (-(~x));
}
这篇关于Add 1 to a given number的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!