2017华为面试算法题小结

9月份去参加华为面试,问了项目经验后,直接让写程序,问了两道题目1.完成strcpy函数 2.实现大数相加 都是基本题,但还是有比较做个总结

1. 关于strcpy的实现(10分):

【4分代码】

void strcpy(char *strDest,char *strSrc)
{
	while((*strDest++ = *strSrc++) != '\0');
}

【6分代码】

void strcpy(char *strDest,const char *strSrc)
{
	while((*strDest++ = *strSrc++) != '\0');
}

【8分代码】

void strcpy(char *strDest,const char *strSrc)

{
	assert((strDest!=NULL) && (strSrc!=NULL))
	while((*strDest++ = *strSrc++) != '\0');
}

[10分代码]

char* strcpy(char *strDest,const char *strSrc)
{
	char *r = strDest;
	assert((strDest!=NULL) && (strSrc!=NULL))
	while((*strDest++ = *strSrc++) != '\0');
	return r;
}

2.关于大数相加的实现代码如下:

#include <iostream>
#include<string>
#include<algorithm>
using namespace std;

string & remove_zero(string &a)
{
	if (a[0] != '0')
		return a;
	int i = 0;
	while (i<a.length() && a[i]=='0')
	{
		i++;
	}
	a = a.substr(i, a.length() - 1);
	return a;
}
int main()
{
	string a;
	string b;
	cin >> a >> b;
	//去掉前导零
	string add1 = remove_zero(a);
	string add2 = remove_zero(b);

	//反转
	reverse(add1.begin(),add1.end());
	reverse(add2.begin(), add2.end());
	//相加
	int len1 = add1.length();
	int len2 = add2.length();

	int len = len1;
	if (len1 < len2)
	{
		len = len2;
	}
	int carry = 0;
	string res = "";
	char cur;
	int i;
	for ( i = 0; i < len;i++)
	{
		int temp1 = 0;
		int temp2 = 0;
		if (i<len1)
			temp1 = add1[i] - '0';
		if (i<len2)
			temp2 = add2[i] - '0';
		int sum = temp1+ temp2 + carry;
		if (sum>9)
		{
			carry = 1; 
			cur = '0' + sum - 10;
		}
		else
		{
			carry = 0;
			cur = '0' + sum;
		}
		res = res + cur;
	}
	//最后一位有进位
	if (carry==1)
	{
		res += '1';
	}
	reverse(res.begin(), res.end());
	cout << res << endl;

	system("pause");
	return 0;
}

运行结果如下:

《2017华为面试算法题小结》

    原文作者:赵卓不凡
    原文地址: https://blog.csdn.net/sgzqc/article/details/52776066
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞