商汤笔试题目

972 阅读2分钟

气到吐血。。。今天笔试题的第一题,算这次已经写了三次了,前两次做时间比较充足,写得比较顺利,就没当回事,今天这一题写得出了点问题,后面时间不够的时候就紧张了,不知道怎么写了。交卷之后还是好气,花点时间写出来了。自己写的垃圾代码,看上去很乱,看了同学的代码,发现别人的代码就很整洁,自己也需要注意一下这方面。

题目:给定两个字符串,将其按照7进制进行相加,返回一个字符串

          如果输入字符串不符合规则,输出“NA”

垃圾代码:

#include<iostream>
#include<string>
#include<algorithm>

using namespace std;

string Sum(string str1, string str2)
{
	int len1 = str1.length();
	int len2 = str2.length();
	string res = "";
	/*if (len1 <= 0 && len2 <= 0)  //这种情况根本不需要单独列出来说,下面可以处理这种情况
	{
		return "NA";
	}
	else if (len1 == 0 && len2 > 0)
	{
		int i;
		for (i = 0; i < len2; i++)
		{
			if (str2[i]<'0' || str2[i]>'6')
				return "NA";
		}
		if (i == len2)
			return str2;
	}
	else if (len1 > 0 && len2 == 0)
	{
		int i;
		for (i = 0; i < len1; i++)
		{
			if (str1[i]<'0' || str1[i]>'6')
				return "NA";
		}
		if (i == len1)
			return str1;
	}
	else
	{*/
		int i = len1 - 1;
		int j = len2 - 1;
		int n = 0;
		while (i >= 0 && j >= 0)
		{
			if (str1[i]<'0' || str1[i]>'6' || str2[j]<'0' || str2[j]>'6')
				return "NA";//不觉得每次都判断很麻烦吗?在进入这个函数之前先判断一下
			int tmp = str1[i]-'0'+str2[j]-'0';
			if (n != 0)
			{
				tmp += n;	
			}
			res += (tmp % 7) + '0';
			n = tmp/ 7;	
			i--;
			j--;
		}
		
		if (i == -1 && j == -1 && n != 0)
		{
			res += n + '0';
		}
		while (i == -1 && j >= 0)
		{
			if (str2[j]<'0' || str2[j]>'6')
				return "NA";
			if (n != 0)
			{
				str2[j] += n;
				n = 0;
			}
			res += str2[j];
			j--;
		}
		while (i >=0 && j == -1)
		{
			if (str1[i]<'0' || str1[i]>'6')
				return "NA";
			if (n != 0)
			{
				str1[i] += n;
				n = 0;
			}
			res += str1[i];
			i--;
		}
		
	
//}
	reverse(res.begin(), res.end());
	return res;
}

int main()
{
	string str1;
	string str2;
	cin >> str1 >> str2;
	string res="";
	res = Sum(str1, str2);
	cout << res << endl;
	system("pause");
	return 0;
}

优化后代码:

#include<iostream>
#include<string>
#include<algorithm>

using namespace std;

string Sum(string str1, string str2)
{
	int len1 = str1.length();
	int len2 = str2.length();
	string res = "";
	int i = len1 - 1;
	int j = len2 - 1;
	int n = 0;
	while (i >= 0 && j >= 0)
	{
		int tmp = str1[i]-'0'+str2[j]-'0';
		if (n != 0)
		{
			tmp += n;	
		}
		res += (tmp % 7) + '0';
		n = tmp/ 7;	
		i--;
		j--;
	}
		
	if (i == -1 && j == -1 && n != 0)
	{
		res += n + '0';
	}
	while (i == -1 && j >= 0)
	{
		if (n != 0)
		{
			str2[j] += n;
			n = 0;
		}
		res += str2[j];
		j--;
	}
	while (i >=0 && j == -1)
	{
		if (n != 0)
		{
			str1[i] += n;
			n = 0;
		}
		res += str1[i];
		i--;
	}
	reverse(res.begin(), res.end());
	return res;
}

int main()
{
	string str1;
	string str2;
	cin >> str1 >> str2;
	for (auto c:str1)
	{
		if (c<'0' || c>'6')
		{
			cout << "NA" << endl;
			return 0;
		}
			
		
	}
	for (auto c : str2)
	{
		if (c<'0' || c>'6')
		{
			cout << "NA" << endl;
			return 0;
		}	
	}
	string res="";
	res = Sum(str1, str2);
	cout << res << endl;
	system("pause");
	return 0;
}