现在的位置: 首页 > 综合 > 正文

位运算做加法

2017年12月23日 ⁄ 综合 ⁄ 共 466字 ⁄ 字号 评论关闭

蛮经典的一个题了,老是忘,记下来:

 

#include<iostream>
 #include<string>
 using namespace std;
 
 /**********************************************
 *    Add Without use + - * /
 **********************************************/
 int PlusWithoutArithmetic(int a,int b)
 {
     if(b == 0)
         return a;
 
     int sum = a ^ b;
     int temp = (a & b)<<1;
 
     return PlusWithoutArithmetic(sum,temp);
 }
 
 int main()
 {
     cout<<"Enter the two numbers:"<<endl;
     int num1 = 0;
     int num2 = 0;
     cin>>num1>>num2;
 
     cout<<"the plus result is:"<<endl;
     cout<<PlusWithoutArithmetic(num1,num2)<<endl;
 
     return 0;
 }

抱歉!评论已关闭.