leetcode_c++:哈希:Fraction to Recurring Decimal(166)

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);
    }
}







评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值