Fraction to Recurring Decimal——数值处理&&哈希表
2024-09-11 10:34:29
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;
}
};
最新文章
- IOS与Android APP界面设计规范要点
- 用val()获取与设置input的值
- redis pool config的配置参数
- VC++界面编程之--阴影窗口的实现详解
- A+B问题 涉及EOF
- UC编程之网络通信(TCP/UDP)
- LinkedList类
- babel 插件编写
- 咸鱼入门到放弃12--Filter(过滤器)*
- day4-python基础-数据类型
- tp3.2 D 和 M 的区别
- 字符串(string)的常用语法和常用函数
- cf571B Minimization (dp)
- Docker学习笔记1 -- 刚入手docker时的几个命令
- 通过SQL Server 2008 访问Oracle 10g
- sql随机查询数据语句(NewID(),Rnd,Rand(),random())
- 【转】fiddler抓包时出现了tunnel to ......443 解密HTTPS数据
- MySQL Crash Course #18# Chapter 26. Managing Transaction Processing
- [翻译] About Core Image
- 基于Netty4.1.29.Final的helloworld实现.使用idea
热门文章
- bzoj1263: [SCOI2006]整数划分(高精度+构造)
- 跳跃表 https://61mon.com/index.php/archives/222/
- 单例 ------ JAVA实现
- Bigbluebutton中文乱码问题
- Kubernetes - Start containers using Kubectl
- Eclipse srever起来时,时间超过45s。
- [LeetCode] 13. Roman to Integer ☆☆
- 三星 C7恢复 出厂设置
- 【Foreign】Game [博弈论][DP]
- 【51NOD-0】1006 最长公共子序列Lcs