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

2015年校招--华为上机笔试题--大数相乘

时间:2014-09-13 22:52:06      阅读:264      评论:0      收藏:0      [点我收藏+]

标签:2015年校招   华为上机笔试题   大数相乘   

#include "stdafx.h"
#include<string>
#include<iostream>
using namespace std;

void add(string &sum,string temp)
{
	int len1=sum.size();
	int len2=temp.size();

	int jw=0;
	int i,j;
	for(i=len1-1,j=len2-1;i>=0 && j>=0;i--,j--)
	{
		int a=sum[i]-'0';
		int b=temp[j]-'0';
		int c=a+b+jw;
		if(c>9)
		{
			sum[i]=c-10+'0';
			jw=1;
		}
		else
		{
			sum[i]=c+'0';
			jw=0;
		}
	}
	if(jw==1)
	{
		while(jw==1)
		{
			int a=sum[j]-'0';
			a++;
			if(a>9)
			{
				sum[j]='0'+a-10;
				jw=1;
			}
			else
			{
				sum[j]='0'+a;
				jw=0;
			}
		}
	}
}

string mul(string sum,char ch,int off)
{
	int len=sum.size();
	int a=ch-'0';
	int jw=0;
	for(int i=len-1;i>=0;i--)
	{
		int b=sum[i]-'0';
		int c=a*b+jw;
		jw=c/10;
		int d=c%10;
		sum[i]=d+'0';
	}
	if(jw!=0)
	{
		sum=string(1,'0'+jw)+sum;
	}
	sum=sum+string(off,'0');
	return sum;
}

string get_result(string str1,string str2)
{
	string sum(200,'0');
	int len=str2.size();
	for(int i=len-1;i>=0;i--)
	{
		string temp=mul(str1,str2[i],len-1-i);
		add(sum,temp);
	}

	int index=sum.find_first_not_of('0');
	sum=sum.substr(index);
	return sum;
}

int main()
{
	string str1="56789";
	string str2="555432";

	string result=get_result(str1,str2);

	cout<<result<<endl;
	system("pause");
	return 0;    
}

2015年校招--华为上机笔试题--大数相乘

标签:2015年校招   华为上机笔试题   大数相乘   

原文地址:http://blog.csdn.net/cjc211322/article/details/39255801

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