思路:
这道题只a30+%,最后发现是小数0没处理,但此外其实忽略了最大的问题就是是个大数题目,长度在200位
错误版:巨坑1:c++字符串拼接不支持数字,而且字面值字符串拼接也要和string对象间隔才可以实现(记成了数值和string相间,在拼接字符串找错花了很多时间。。。python/java。。。)
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
using namespace std;
class Solution {
public:
int decode(int n){
int sum=0;
int basic = 1;
while (n>0) {
int tempt = n % 10 * basic;
sum += tempt;
n = n / 10;
basic = basic * 9;
}
return sum;
}
string encode(int n){
stringstream ss;
string result = "";
while(n > 0){
int tempt = n % 9;
ss<<tempt<<result;/////////
result = ss.str();
n = n / 9;
ss.str("");
}
return result;
}
string add(string num1, string num2) {
string str_num1_int, str_num2_int, str_num1_flo, str_num2_flo;
int pos1 = num1.find("."), pos2 = num2.find(".");
str_num1_int = num1.substr(0, pos1);
if(pos1 != -1)
str_num1_flo = num1.substr(pos1+1, num1.size()-pos1-1);
else
str_num1_flo = "0";
str_num2_int = num2.substr(0, pos2);
if(pos2 != -1)
str_num2_flo = num2.substr(pos2+1, num2.size()-pos2-1);
else
str_num2_flo = "0";
int num1_int, num1_flo, num2_int, num2_flo;
stringstream ss;
ss<<str_num1_int;
ss>>num1_int;
ss.clear();
ss<<str_num2_int;
ss>>num2_int;
ss.clear();
ss<<str_num1_flo;
ss>>num1_flo;
ss.clear();
ss<<str_num2_flo;
ss>>num2_flo;
ss.clear();
cout<<num1_int<<" "<<num1_flo<<endl;
cout<<num2_int<<" "<<num2_flo<<endl;
string flo = encode(decode(num1_flo)+decode(num2_flo));
int add=0;
string integer;
if(flo.size()>str_num1_flo.size() ||flo.size()>str_num2_flo.size()){
ss<<flo[0];
ss>>add;
flo = flo.substr(1, flo.size()-1);
}
integer = encode(decode(num1_int) + decode(num2_int) + decode(add));
cout<<integer<<" "<<flo;
return integer + ((flo=="")?"":"."+flo);
}
};
int main() {
Solution s;
cout<<s.add("1.5", "2.50");
return 0;
}大数相加版(发现以前对一些东西的印象会很大影响对其后续,敲了才发现大数相加也不过如此,以前老是觉得繁琐的像噩梦)
class Solution {
public:
string add(string num1, string num2) {
int pos1 = num1.find(".");
int pos2 = num2.find(".");
string n1_int = num1.substr(0, pos1);
string n2_int = num2.substr(0, pos2);
string n1_flo = ((pos1==-1)?"":num1.substr(pos1+1, num1.size()-1-pos1));
string n2_flo = ((pos2==-1)?"":num2.substr(pos2+1, num2.size()-1-pos2));
if(n1_flo.size()<n2_flo.size()){
swap(n1_flo, n2_flo);
}
int i=n2_flo.size()-1;
int in = 0;
while(i>=0){
int b = (n1_flo[i] + n2_flo[i] - 2*'0' + in)%9;
in = (n1_flo[i] + n2_flo[i] - 2*'0' + in) / 9;
n1_flo[i] = b + '0';
i--;
}
if(n1_int.size()<n2_int.size()){
swap(n1_int, n2_int);
}
i = 0;
while(i<n2_int.size()){
int b = (n1_int[n1_int.size()-1-i] + n2_int[n2_int.size()-1-i] - 2*'0' + in)%9;
in = (n1_int[n1_int.size()-1-i] + n2_int[n2_int.size()-1-i] - 2*'0' + in) / 9;
n1_int[i] = b + '0';
i++;
}
i = n1_int.size()-i-1;
while(i!=-1&&in){
int b = (n1_int[i] - '0' + in) % 9;
in = (n1_int[i] - '0' + in) / 9;
i--;
}
if(i==-1&&in!=0){
n1_int = to_string(in) + n1_int;
}
return n1_int + ((n1_flo.size()>0)?("."+n1_flo):"");
}
};
京公网安备 11010502036488号