C++ 中分数到循环小数的转换
假设我们有两个整数代表分数的分子和分母,我们需要找到分数的字符串格式。如果小数部分是循环的,则将循环部分用括号括起来。例如,如果分子是 2,分母是 3,则输出为“0.(6)”
为了解决这个问题,我们将遵循以下步骤:
如果分子为 0,则返回 0
定义一个数组 ans
如果分子 < 0 且分母 > 0 或分子 = 0 且分母 < 0,则将负号 ‘-’ 插入 ans 数组
除数 := |分子|,被除数 := |分母|,余数 := 除数 mod 被除数
x := 除数 / 被除数 的字符串
将 x 中的每个字符插入 ans 数组
如果余数 = 0,则返回 ans 数组作为字符串。
在 ans 中插入点 ‘.’
定义一个映射 m
当余数不为 0 时
如果余数存在于 m 中,则
在 ans 的 m[余数] 索引处插入左括号
在 ans 的末尾插入右括号
中断循环
否则
m[余数] := ans 的大小
余数 := 余数 * 10
将 (余数 / 被除数) 作为字符插入 ans
余数 := 余数 mod 被除数
返回 ans 数组作为字符串。
让我们看下面的实现来更好地理解:
示例
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
string fractionToDecimal(int numerator, int denominator) {
if(numerator == 0)return "0";
vector <char> ans;
if(numerator < 0 && denominator > 0 || numerator > 0 && denominator < 0)ans.push_back('-');
long divisor = labs(numerator);
long dividend = labs(denominator);
long remainder = divisor % dividend;
string x = to_string(divisor/dividend);
for(int i = 0; i < x.size(); i++){
ans.push_back(x[i]);
}
if(remainder == 0){
return string(ans.begin(), ans.end());
}
ans.push_back('.');
map <int, int> m;
while(remainder != 0){
if(m.find(remainder)!=m.end()){
ans.insert(ans.begin() + m[remainder], '(');
ans.push_back(')');
break;
}else{
m[remainder] = ans.size();
remainder *= 10;
ans.push_back((remainder / dividend) + '0');
remainder %= dividend;
}
}
return string(ans.begin(), ans.end());
}
};
main(){
Solution ob;
cout << ((ob.fractionToDecimal(100,6)));
}输入
100 6
输出
16.(6)
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP