首页 > 学院 > 开发设计 > 正文

剑指offer——不用加减乘除做加法

2019-11-08 02:11:05
字体:
来源:转载
供稿:网友

写一个函数,求两个整数之和,要求在函数体内不得使用+、-、*、/四则运算符号

第一直觉是使用位运算,但是位运算没有进位,只要加上进位的为题就可以了

PRivate static int add(int n1, int n2) { int num, temp; do { num = n1 ^ n2; temp = (n1 & n2) << 1; n1 = num; n2 = temp; } while (n2 != 0); return num; }

然后顺便解决一下减法的问题:减法可以使用加上负数的原则。~n+1就是n的负数。

private static int decrease(int n1, int n2) { int result=add(n1,~n2+1); return result; }
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表