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)".

Hint:

No scary math, just apply elementary math knowledge. Still remember how to perform a long division?

这题就是按定义做。

如果不能整除,就不断进行余数补零除以除数。

维护一个映射表map<long long, int> m, 用来记录每个余数对应返回值ret中的位置。

(1)当出现重复的余数r时,说明找到了循环体,根据m[r]找到ret中位置,加上相应的'('和')'将循环体括起来即可返回。

(2)当余数r为0时,返回ret。

注意点:可能出现INT_MIN/-1的越界情况,因此第一步现将int转为long long int

class Solution {
public:
string fractionToDecimal(int numerator, int denominator) {
if(denominator==)
return "";
if(numerator==)
return "";
string res;
long long num=numerator;
long long den=denominator;
if((num<)^(den<))
{
res+="-";
num=abs(num);
den=abs(den);
}
long long temp=num/den;
res+=to_string(temp);
if (num%den==)
return res;
res+=".";
temp=num%den;
map<long long,int> m;
while(temp!=)
{
if(m.find(temp)!=m.end())
{
res.insert(m[temp], , '('); //insert (iterator p, size_t n, char c);
res += ')';
return res;
}
m[temp] = res.size();
temp*=;
res+=to_string(temp/den);
temp%=den;
}
return res;
}
};

最新文章

  1. IOS与Android APP界面设计规范要点
  2. 用val()获取与设置input的值
  3. redis pool config的配置参数
  4. VC++界面编程之--阴影窗口的实现详解
  5. A+B问题 涉及EOF
  6. UC编程之网络通信(TCP/UDP)
  7. LinkedList类
  8. babel 插件编写
  9. 咸鱼入门到放弃12--Filter(过滤器)*
  10. day4-python基础-数据类型
  11. tp3.2 D 和 M 的区别
  12. 字符串(string)的常用语法和常用函数
  13. cf571B Minimization (dp)
  14. Docker学习笔记1 -- 刚入手docker时的几个命令
  15. 通过SQL Server 2008 访问Oracle 10g
  16. sql随机查询数据语句(NewID(),Rnd,Rand(),random())
  17. 【转】fiddler抓包时出现了tunnel to ......443 解密HTTPS数据
  18. MySQL Crash Course #18# Chapter 26. Managing Transaction Processing
  19. [翻译] About Core Image
  20. 基于Netty4.1.29.Final的helloworld实现.使用idea

热门文章

  1. bzoj1263: [SCOI2006]整数划分(高精度+构造)
  2. 跳跃表 https://61mon.com/index.php/archives/222/
  3. 单例 ------ JAVA实现
  4. Bigbluebutton中文乱码问题
  5. Kubernetes - Start containers using Kubectl
  6. Eclipse srever起来时,时间超过45s。
  7. [LeetCode] 13. Roman to Integer ☆☆
  8. 三星 C7恢复 出厂设置
  9. 【Foreign】Game [博弈论][DP]
  10. 【51NOD-0】1006 最长公共子序列Lcs