View Code of Problem 132

#include<iostream>
#include<cstdio>
#include<stdlib.h> 

using namespace std;

int main()
{
	string a, b;
	while(scanf("%s %s", a.c_str(), b.c_str()) != EOF)
	{
		string x1, x2, y1, y2, s1, s2;
		int i;
		for(i = 0; a[i] != '.' && a[i] != '\0'; i++)
			x1 = x1 + a[i];
		if(a[i] == '.')
			for(i++; a[i] != '\0'; i++)
				x2 = x2 + a[i];
		for(i = 0; b[i] != '.' && b[i] != '\0'; i++)
			y1 = y1 + b[i];
		if(b[i] == '.')
			for(i++; b[i] != '\0'; i++)
				y2 = y2 + b[i];
				
		if(x1.length() < y1.length())
		{
			int d = y1.length() - x1.length();
			while(d--)
				x1 = '0' + x1;
		}
		else
		{
			int d = x1.length() - y1.length();
			while(d--)
				y1 = '0' + y1;
		}
		if(x2.length() < y2.length())
		{
			int d = y2.length() - x2.length();
			while(d--)
				x2 = x2 + '0';
		}
		else
		{
			int d = x2.length() - y2.length();
			while(d--)
				y2 = y2 + '0';
		}
		
		int carry = 0;
		for(i = x2.length()-1; i >= 0; i--)
		{
			x2[i] -= '0';
			y2[i] -= '0';
			char c = (x2[i] + y2[i] + carry) % 10 + '0';
			if(x2[i] + y2[i] + carry >= 10)
				carry = 1;
			else
				carry = 0;
			s2 = c + s2;
		}
		for(i = x1.length()-1; i >= 0; i--)
		{
			x1[i] -= '0';
			y1[i] -= '0';
			char c = (x1[i] + y1[i] + carry) % 10 + '0';
			if(x1[i] + y1[i] + carry >= 10)
				carry = 1;
			else
				carry = 0;
			s1 = c + s1;
		}
		if(carry == 1)
			s1 = '1' + s1;
			
		for(i = 0; i < s1.length(); i++)
			if(s1[i] != '0')
				break;
		if(i != s1.length())
			s2 = s2.substr(i, s2.length());
		else
			s2 = '0';
		for(i = s2.length()-1; i >= 0; i--)
			if(s2[i] != '0')
				break;
		if(i >= 0)
			s2 = s2.substr(0, i+1);
			
		if(i < 0)
			printf("%s\n", s1.c_str());
		else
			printf("%s.%s\n", s1.c_str(), s2.c_str());
		
	}
	return 0;
}

Double click to view unformatted code.


Back to problem 132