趋势科技笔试第一题(实现两个超长非负数之和)
#include <iostream> #include <vector> #include <algorithm> using namespace std; string add(string &a1, string &a2) { int len1 = a1.size(); int len2 = a2.size(); int shi_len1=0, shi_len2=0, xiao_len1=0, xiao_len2=0; int i = len1-1; while (a1[i] != '.') { xiao_len1++; i--; } shi_len1 = len1 - xiao_len1 - 1; //整数位以及小数的长度 i = len2-1; while (a2[i] != '.') { xiao_len2++; i--; } shi_len2 = len2 - xiao_len2 - 1; int shi_len = max(shi_len1, shi_len2); int xiao_len = max(xiao_len1,xiao_len2); vector<int>a4(xiao_len,0); //存小数 i = 0; while (i < xiao_len) { if (i < xiao_len1) a4[i] += a1[shi_len1 + 1 + i] - '0'; if(i<xiao_len2) a4[i] += a2[shi_len2 + 1 + i] - '0'; i++; } vector<int>a3(shi_len ,0); //存整数 i = shi_len-1; while (i>=0) { if (shi_len1 > 0) a3[i] += a1[--shi_len1] - '0'; if (shi_len2 > 0) a3[i] += a2[--shi_len2] - '0'; i--; } int carry = 0; //防止两个相加以后和大于等于10,字符只能表示0~9,两位数的要拆出来 for (i = xiao_len - 1; i >= 0; i--) { a4[i] += carry; carry = a4[i]/10; a4[i] %= 10; } if (carry >= 1) //考虑小数点进位问题 a3[shi_len-1] += carry; carry = 0; for (i = shi_len - 1; i >= 0; i--) { a3[i] += carry; carry = a3[i] / 10; a3[i] %= 10; } int len = shi_len + xiao_len; //拼合 string a; for (i = 0; i <= len; i++) { if (i < shi_len) a.push_back( a3[i] + '0'); else if (i == shi_len) a.push_back( '.'); else a.push_back( a4[i - shi_len - 1] + '0'); } return a; } int main() { string a1 = "1234.43"; string a2 = "12347.581"; string a3; a3=add(a1, a2); int len = a3.size(); for (int i = 0; i < len; i++) cout << a3[i]; system("pause"); return 0; }
#趋势科技##笔试题目#