阿里巴巴在线笔试编程题2题

前言:上周五参加了阿里巴巴的在线笔试,包含半小时10条选择题和一小时2条编程题。

题目1:

有两个非负数a和b,求两者的和。注意a和b可能是小数,输出结果不包含多于的0。

输入:

12.3 5

输出:

17.5

参考代码:

#include<iostream>
#include<string>
using namespace std;
string first, second, ans;

string Sum(string a, string b){
	int len1 = a.size();
	int len2 = b.size();
	int len = (len1 > len2 ? len1 : len2);
	for(int i = 0; i < len; i++) ans += "0";
	int tmp, c = 0;
	for(int i = len-1; i >= 0; i--){
		if(a[i] == '.'){
			ans[i] = '.';
	 		continue;
		}
		tmp = a[i]-'0' + b[i]-'0' + c;
		if(tmp > 9){
			tmp -= 10;
			c = 1;
		}else{
			c = 0;
		}
		ans[i] = tmp + '0';
	}
	if(c > 0) ans = "1" + ans;
	return ans;
}

bool check(string b){
	int len = b.size();
	for(int i = 0; i < len; i++){
		if(b[i] != '.' && (b[i] < '0' || b[i] > '9')){
			return "false";
		}
	}
}

void cal(string a, int& zhengshu, int& xiaoshu){  //大数a, a的整数位数, a的小数位数
	int len = a.size();
	int i;
	for(i = 0; i < len; i++){
		if(a[i] == '.'){
			zhengshu = i;
			xiaoshu = len-i-1;
			break;
		}
	}
	if(i == len){
 		zhengshu = len;
 		xiaoshu = 0;
	}
}

void out(string a){  //大数a
	int len = a.size();
	int mowei = len-1;
	while(mowei > 0 && a[mowei] == '0') mowei--;
	if(a[mowei] == '.'){
		mowei--;
	}
	for(int i = 0; i <= mowei; i++){
		cout << a[i];
	}
	cout << endl;
}

int main(){
	cin >> first >> second;
	if(check(first) || check(second)){
		cout << "false" << endl;
		exit(0);
	}
	
	int zhengshu1, xiaoshu1, zhengshu2, xiaoshu2, zs, xs;
	cal(first, zhengshu1, xiaoshu1);  //获取first的整数位数zhengshu,小数位数xiaoshu1 
	cal(second, zhengshu2, xiaoshu2);
		
	if(zhengshu1 > zhengshu2){
		zs = zhengshu1;
		for(int i = zhengshu2+1; i <= zhengshu1; i++){
			second = "0" + second;
		}		
	}else{
		zs = zhengshu2;
		for(int i = zhengshu1+1; i <= zhengshu2; i++){
			first = "0" + first;
		}
	}
	
	if(xiaoshu1 > xiaoshu2){
		xs = xiaoshu1;
		for(int i = xiaoshu2+1; i <= xiaoshu1; i++){
			second += "0";
		}
	}else{
		xs = xiaoshu2;
		for(int i = xiaoshu1+1; i <= xiaoshu2; i++){
			first += "0";
		}
	}

	string ans = Sum(first, second);
	
	out(ans);
	return 0;
}

题目2:

给定两个由数字0-9组成的字符数组,如“2345”,“4436”,从这两个数组分别取数,生成新数组。比如生成:44234365,生成方式如下图所示,每个数组取数放入新数组的时候,是按照下标从小到大取得。
 
对于字符数组,定义跨度值:K(c),为数字c最大下标和最小下标之差。比如数字44234365每个数字的K(c)定义如下:
num   2  3 4 5 6  
K(c)    0  2 4 0 0  
请找到一种取合成方式,使得K(c)的总和最小(比如,上例总和为6,但总和并非最小)。打印出最小的K(c) 之和。

输入:
两个0-9组成的字符串first,second
输出:
最小和,是一个int类型
输入范例:
2345
4436
输出范例:

5

第二题没有什么思路,有大神会的话希望可以提供一下思路。

猜你喜欢

转载自blog.csdn.net/li_wei_quan/article/details/80310426