View Code of Problem 132

#include<iostream>
#include<stdio.h>
#include<string>
#include<cstring>
#include<string.h>
#include<algorithm>
using namespace std;

void fun(string a, string &m, string &n) {
	int temp = a.find('.');
	if (temp > 0) {
		m = a.substr(0, temp);
		n = a.substr(temp + 1, a.length() - 1);
	}
	else {
		m = a;
		n = "0";
	}
}

void insertLeft(string &x, string &y) {
	int gap = x.length() - y.length();
	if (gap >= 0) {
		x.insert(0, 1, '0');
		y.insert(0, gap + 1, '0');
	}
	else {
		x.insert(0, -gap + 1, '0');
		y.insert(0, 1, '0');
	}
}

void insertRight(string &x, string &y) {
	int gap = x.length() - y.length();
	if (gap >= 0) {
		while (gap--) {
			y.append("0");
		}
	}
	else {
		gap = -gap;
		while (gap--) {
			x.append("0");
		}
	}
}

string add(string x, string y, int &flag) {
	string result;
	for (int i = x.length()-1;i >= 0;i--) {
		char temp = x[i] + y[i] - '0' + flag;
		if (temp > '9') {
			temp -= 10;
			flag = 1;
		}
		else {
			flag = 0;
		}
		result += temp;
	}
	return result;
}

int main() {
	string a, b, m, n, p, q;
	while (cin >> a >>b) {
		int flag = 0;
		fun(a, m, n);
		fun(b, p, q);
		insertLeft(m, p);
		insertRight(n, q);
		string right = add(n, q, flag);
		string left = add(m, p,flag);
		if (left[left.length() - 1] == '0') {
			left.erase(left.length() - 1,1);
		}
		while (right[0] == '0') {
			right.erase(0, 1);
		}
		for (int i = left.length() - 1;i >= 0;i--) {
			cout << left[i];
		}
		int x = 1;
		for (int i = right.length() - 1;i >= 0;i--) {
			if (x) {
				cout << ".";
				x = 0;
			}
			cout << right[i];
		}
		cout << endl;
	}
}

Double click to view unformatted code.


Back to problem 132