Given two integers representing the numerator and denominator of a fraction, return the fraction in string format.
If the fractional part is repeating, enclose the repeating part in parentheses.
For example,
Given numerator = 1, denominator = 2, return “0.5”.
Given numerator = 2, denominator = 1, return “2”.
Given numerator = 2, denominator = 3, return “0.(6)”.
算法
o(n^2)
//
// main.cpp
// CplusplusTest
//
// Created by mijian on 16/7/1.
// Copyright © 2016年 mijian. All rights reserved.
//
#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <limits.h>
#include <unordered_map>
#include <sstream>
using namespace std;
/*
test case
>0/2
>1/0
>1/3
>2/4
>100/2
-1/4
1/-4
25/99(0.2525...)
1/7=(0.1428571)
>1/17=0.(05882352941117647)
*/
class Solution {
public:
string fractionToDecimal(int numerator, int denominator) {
string reslut;
// 0 的情况
if(denominator==0) {return reslut;}
if(numerator==0) {return "0";}
//使用longlong类型
long long n= numerator;
long long d= denominator;
// 处理负数
bool sign=((float)numerator/denominator>=0);
if(n<0){n=-n;}
if(d<0){d=-d;}
if(sign==false)
reslut.push_back('-');
long long remainder=n%d;
long long division = n/d;
ostringstream oss;
oss<<division;
reslut+=oss.str();
if(remainder==0)
return reslut;
//remainder has value ,the result si a float
reslut.push_back('.');
// map recored the result
map<long long, int> rec;
for(int pos=reslut.size();remainder!=0;pos++,remainder=(remainder*10)%d){
if(rec.find(remainder)!=rec.end()){
reslut.insert(reslut.begin()+rec[remainder],'(');
reslut.push_back(')');
return reslut;
}
rec[remainder]=pos;
reslut.push_back((remainder*10)/d+'0');
}
return reslut;
}
void test(int num,int demo){
cout<<"numerator : "<<num<<"\t denomonator: "<<demo<<"\treslut: "<<fractionToDecimal(num,demo)<<endl;
}
};
int main(int argc, char** argv){
Solution s;
s.test(1,2);
s.test(1,0);
s.test(0,1);
s.test(1,7);
s.test(1,17);
if(argc >2){
int num=atoi(argv[1]);
int deno=atoi(argv[2]);
s.test(num,deno);
}
}