码迷,mamicode.com
首页 > 其他好文 > 详细

Add Binary

时间:2014-12-21 11:30:10      阅读:254      评论:0      收藏:0      [点我收藏+]

标签:

该题答案如下:

class Solution {
public:
    string addBinary(string a, string b) {
       string::reverse_iterator itea,iteb;
	   string result;
	   char temp;
	   int flag =0;
	   for(itea = a.rbegin(), iteb = b.rbegin(); itea != a.rend()&& iteb !=b.rend(); itea++, iteb++ )
	   {
         temp = GetResult(*itea,*iteb,flag);
		 if(temp >= 2)
		 {
           flag =1;
		   temp = temp%2;
		 }
		 else
		 {
          	flag =0;
		 }
		 result.insert(result.begin(),temp + ‘0‘);
	    }
	   for(; itea != a.rend(); itea++)
      	{
      	   temp = GetResult(*itea,‘0‘,flag);
      	   if(temp >= 2)
      	   {
      		 flag =1;
      		 temp = temp%2;
      	   }
      	   else
      	   {
      		  flag =0;
      	   }
      	   result.insert(result.begin(),temp + ‘0‘);
      	}
	   for(; iteb != b.rend(); iteb++)
	   {
			 temp = GetResult(*iteb,‘0‘,flag);
			 if(temp >= 2)
			 {
			   flag =1;
			   temp = temp%2;
			 }
			 else
			 {
				flag =0;
			 }
			result.insert(result.begin(),temp + ‘0‘);
	   }
	   if(flag != 0)
	   result.insert(result.begin(),‘1‘);

	   return result;
        
    }
	char GetResult(char a, char b,int flag)
	{
	   char result;
	   a = a -‘0‘;
	   b = b - ‘0‘;
	   result = a + b + flag;
	   return result;

	}
};

 

Add Binary

标签:

原文地址:http://www.cnblogs.com/xgcode/p/4176235.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!