本文主要是介绍面试题大数相加相减,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
根据http://www.cnblogs.com/caixu/archive/2011/09/26/2192189.html这个修改了相加函数,并增加了相减函数。
#include <iostream>
#include <string>
using namespace std;const int MAX_LENGTH = 1000;
class ds
{
public:
void add(string x, string y);
void sub(string x, string y);
private :
string s1,s2;
};
void ds::sub(string x, string y)
{
int length1 = x.length();
int length2 = y.length();
int long_length;
int short_length;
string bigger_string;
string smaller_string;
int i = 0;
int big = -1;
if (length1 > length2) {
bigger_string = x;
smaller_string = y;
long_length = length1;
short_length = length2;
} else if (length1 < length2) {
bigger_string = y;
smaller_string = x;
long_length = length2;
short_length = length1;
big = 2;
} else {
for (i = 0; i< length1; i++) {
int sub_value = x[length1-1-i] - y[length1-1-i];
if(sub_value > 0) {
bigger_string = x;
smaller_string = y;
big = 0;
break;
}
else if (sub_value < 0) {
bigger_string = y;
smaller_string = x;
big = 1;
break;
}
else{}
}
if (-1 == big) {
cout << "0" << endl;
return;
}
}
int sub = 0;
int flag = 0;
int sub_sum[MAX_LENGTH];
for (i = 0; i<short_length;i++) {
sub = bigger_string[long_length-1-i] - smaller_string[short_length-1-i];
if (sub <0) {
sub += 10;
flag = 1;
} else {
flag = 0;
}
if(1 == flag)
bigger_string[long_length-1-i-1] -= ('1' - '0');
sub_sum[i] = sub;
}
for(i; i<long_length; i++) {
sub_sum[i] = bigger_string[long_length-1-i] - '0';
}
if ( big > 0) {
cout << "-";
}
int str_flag = 0;
for (i--; i>=0;i--) {
if (0 == str_flag &&(0 == (sub_sum[i] - '0')))
;
else
cout << sub_sum[i];
}
}
void ds::add(string x, string y)
{
int flag = 0;
int i;
int length1 = x.length();
int length2 = y.length();
string long_string;
string short_string;
int short_length;
int long_length;
if (length1 >length2) {
long_string = x;
short_string = y;
short_length = length2;
long_length = length1;
}
else {
long_string = y;
short_string = x;
short_length = length1;
long_length = length2;
}
cout << "long is " << long_string << "length is " << long_length << ", short is " << short_string << ",short length is " << short_length<<endl;
int add_sum[MAX_LENGTH];
int sum = 0;
for (i = 0; i<short_length;i++) {
sum = long_string[long_length-1-i] - '0' + short_string[short_length-1-i] - '0' + flag;
if (sum >= 10) {
sum -= 10;
flag = 1;
} else {
flag = 0;
}
add_sum[i] = sum;
}
for (; i<long_length;i++) {
sum = long_string[long_length-1-i] - '0' + flag;
if (sum >= 10) {
sum -= 10;
flag = 1;
} else {
flag = 0;
}
add_sum[i] = sum;
}
if (flag == 1)
add_sum[i++] = 1;
for(i=i--;i>= 0;i--)
cout << add_sum[i];
}
int main()
{
ds dashu;
string x1,x2;
cout<<"please input two word:" <<endl;
cin >>x1>>x2;
int n1=x1.length();
int n2=x2.length();
if (n1==n2)
dashu.equal(x1,x2,n1,n2);
else
dashu.nequal(x1,x2,n1,n2);
dashu.add(x1, x2);
cout <<endl;
cout<<"please input two word:" <<endl;
cin >>x1>>x2;
dashu.sub(x1, x2);
cout <<endl;
return 0;
}
这篇关于面试题大数相加相减的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!