166. Fraction to Recurring Decimal -- 将除法的商表示成字符串(循环节用括号表示)
2016-08-24 09:46
393 查看
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)".
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)".
string fractionToDecimal(int numerator, int denominator) { string result; //deal with the `ZERO` cases if (denominator == 0){ return result; } if (numerator == 0) { return "0"; } //using long long type make sure there has no integer overflow long long n = numerator; long long d = denominator; //deal with negtive cases bool sign = ((float)numerator/denominator >= 0); if ( n < 0 ){ n = -n; } if ( d < 0 ){ d = -d; } if (sign == false){ result.push_back('-'); } long long remainder = n % d; long long division = n / d; ostringstream oss; oss << division; result += oss.str(); if (remainder == 0){ return result; } //remainder has value, the result is a float result.push_back('.'); //using a map to record all of reminders and their position. //if the reminder appeared before, which means the repeated loop begin, //then, get the place from map to insert "(". //(In C++11, it's better to use unordered_map ) map<long long, int> rec; for (int pos=result.size(); remainder!=0; pos++, remainder=(remainder*10)%d ) { if (rec.find(remainder) != rec.end()) { result.insert(result.begin()+rec[remainder], '('); result.push_back(')'); return result; } rec[remainder] = pos; result.push_back((remainder*10)/d + '0'); } return result; }
相关文章推荐
- Java 初始化变量顺序的细节
- linux mail 命令 (收发邮件)
- <sdut-ACM>交叉排序
- Ubuntu14.04设置启动进入字符界面
- leetcode No109. Convert Sorted List to Binary Search Tree
- Rtrofit2源码解析
- Centos 7防火墙firewalld开放80端口
- 2015-2016 ACM-ICPC Northeastern European Regional Contest (NEERC 15)
- Codeforces Round #353 (Div. 2) C. Money Transfers (贪心)
- Delphi 操作Flash D7~XE10都有 导入Activex控件 shockwave
- Linux服务器安全配置
- linux中find命令的用法
- find命令中的选项解释
- 常见例题:输出所有可见ASCII码
- AngularJs ngIf、ngSwitch、ngHide/ngShow
- 遍历文件夹找出所有.java文件(递归)
- Light OJ 1138 (二分查找+分解阶乘)
- iOS 获取私有api的方法
- hbase_2
- POJ 3420 Quad Tiling(轮廓线DP+矩阵快速幂)