二进制运算及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;

typedef string ElemType;
typedef string ElemTypeS;
/*typedef为C语言的关键字,作用是为一种数据类型定义一个新名字,
这里的数据类型包括内部数据类型(int,char等)和自定义的数据类型(struct等)。
typedef本身是一种存储类的关键字,与auto、extern、static、register等关键字不能出现在同一个表达式中*/
template <typename _A, typename _B>
_A Sum(_B a, _B b);

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

	ElemTypeS a = "11", b = "1";
	ElemType ans = Sum<ElemType, ElemTypeS>(a, b);
	cout << ans << " ";
	/
	system("PAUSE ");
	return 0;
}


template <typename _A, typename _B>
_A Sum(_B a, _B b)
{
	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');//在下标为0的位置,插入1个字符sum+'0'
	}
	if (d){
		ans.insert(0, 1, '1');
	}
	return ans;

}

算法分析:

多模板函数,typedef数据类型定义。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值