二进制运算C++

算法原理:

1.先补零,使字符串位数相等

2.ASCAII编码操作字符串,进位暂存。

算法实现:

/ LeetXodeTest.cpp : 定义控制台应用程序的入口点。

#include "stdafx.h"
#include <iostream>
#include <vector>
#include<array>
#include<memory>
#include<string>
#include < unordered_map >
using namespace std;


int _tmain(int argc, _TCHAR* argv[])
{

	string a = "11", b = "1";

	int a_size = a.size(), b_size = b.size(), d = 0, sum;
	string ans = "";
	if (a_size < b_size){
		a.insert(0, b_size - a_size, '0');
	}
	else{
		b.insert(0, a_size - b_size, '0');
	}
	for (int i = a.size() - 1; i >= 0; i--){
		sum = a.at(i) + b.at(i) - 96 + d;
		d = sum >> 1;
		sum &= 1;
		ans.insert(0, 1, sum + '0');
	}
	if (d){
		ans.insert(0, 1, '1');
	}
	cout << ans << " ";
	/////////////////////
	system("PAUSE ");
	return 0;
}

算法分析:

简单实现。

猜你喜欢

转载自blog.csdn.net/qq_36203584/article/details/107771408