不用 +運算符 ,用位操作實現兩數相加(原理+代碼實現)

需要了解的基本概念:

按位操作符:

按位與&

按位異或^

按位左移<<(低位補0)

按位右移(無符號數以及有符號數的邏輯右移,採取高位補0,有符號數的算術右移採取高位補符號位)

異或也叫半加運算,其運算法則相當於不帶進位的二進制加法:二進制下用1表示真,0表示假,則異或的運算法則爲:0⊕0=0,1⊕0=1,0⊕1=1,1⊕1=0(同爲0,異爲1),這些法則與加法是相同的,只是不帶進位,所以異或常被認作不進位加法

 

解決問題的方法:

  • 首先 將兩個數按位異或,得到不含進位的和
  • 通過 按位與 來計算 進位,當兩個數對應位都爲1時產生進位,因此需將按位與的結果左移一位
  • 若進位不爲零,則將 不含進位的和 跟 進位 再次從第1步開始迭代,否則返回結果

例如: 10+6 ,即 1010+0110

1.將 10100110 按位異或 ,得:1100

2.將 10100110 按位與, 得:0010 ,有進位,則左移,得 0100 ,不爲零,開始迭代

3.將 11000100 按位異或,得:1000 

4.將 1100 0100 按位與, 得:0100 ,有進位,則左移,得 1000 ,不爲零,開始迭代

5.將 10001000 按位異或,得:0000

6.將 10001000 按位與, 得:1000 ,有進位,則左移,得10000,不爲零,開始迭代

7.將 000010000 按位異或,得:10000

8.將 000010000 按位與,得:00000,進位爲0,返回結果(即不含進位的和,10000,10+6=16)

用C實現:

#include<stdio.h>

int main()
{
	int A,B,result;
	scanf("%d%d",&A,&B);
	result=add_carry(A,B);
	printf("%d + %d = %d\n",A,B,result)A;
	return 0;
}


int add_carry(int a,int b)    
{
	int sum,carry;
	sum=a^b;            //按位異或
	carry=(a&b)<<1;     //按位與,左移一位
	if(carry==0)        //進位爲0時,返回結果
		return sum;
	add_carry(sum,carry);
}

用C++實現:

#include<iostream>
using namespace std;
int add_carry(int a,int b);

int main()
{
	int A,B,result;
	cin>>A>>B;
	result=add_carry(A,B);
	cout<<A<<" + "<<B<<" = "<<result<<endl;
	return 0;
}


int add_carry(int a,int b)    
{
	int sum,carry;
	sum=a^b;            //按位異或
	carry=(a&b)<<1;     //按位與,左移一位
	if(carry==0)        //進位爲0時,返回結果
		return sum;
	add_carry(sum,carry);
}

用Java實現:

public static int add(int a,int b)
{
	int result;
	int sum=a^b;
	int carry=(a&b)<<1;
	if(carry==0)
		result=sum;
	else
		result=add(sum,carry);
	return result;
}

用Python實現:

def add_carry(a,b):
    sum=a^b;
    carry=(a&b)<<1;
    if carry==0:
        return sum
    else:
        return add_carry(sum,carry)

if __name__ == "__main__":
   a,b=(int(x) for x in input().split())    //輸入a,b 用空格隔開
   print ("a + b = ", add_carry(a,b))

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章