传送门
nowcoder
leetcode
题目描述
写一个函数,求两个整数之和,要求在函数体内不得使用 +、-、*、/
四则运算符号。
C++ 代码 - nowcoder
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
|
class Solution { public: int Add(int num1, int num2) { while (num2 != 0) { int sum = num1 ^ num2; int carry = (num1 & num2) << 1; num1 = sum; num2 = carry; }
return num1; } };
|
C++ 代码 - leetcode
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
|
class Solution { public: int encryptionCalculate(int a, int b) { if (a == 0 || b == 0) { return a == 0 ? b : a; } int sum = a ^ b; int carry = (a & b) << 1; return encryptionCalculate(sum, carry); } };
|