标签:style blog http ar io color os 使用 sp
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,
// to_string example #include <iostream> // std::cout #include <string> // std::string, std::to_string #include<map> using namespace std; class Solution { public: string fractionToDecimal(int numerator, int denominator) { if(numerator==0) return "0"; string result; if(numerator<0 ^ denominator<0 ) result+=‘-‘; //异或,numerator<0和denominator<0仅有一个为真 //转化为正数,INT_MIN转化为正数会溢出,故用long long。long long int n=abs(INT_MIN)得到的n仍然是负的,所以写成下面的形式。 long long int n=numerator,d=denominator; n=abs(n);d=abs(d); result+=to_string(n/d); //整数部分 long long int r=n%d; //余数r if(r==0) return result; else result+=‘.‘; //下面处理小数部分,用哈希表 map<int,int> map; while(r){ //检查余数r是否在哈希表中,是的话则开始循环了 if(map.find(r)!=map.end()){ result.insert(map[r],1,‘(‘); //http://www.cplusplus.com/reference/string/basic_string/insert/ result+=‘)‘; break; } map[r]=result.size(); //这个余数对应于result的哪个位置 //正常运算 r*=10; result+=to_string(r/d); r=r%d; } return result; } }; int main() { Solution s; cout<<s.fractionToDecimal(-1,-2147483648)<<endl; }
标签:style blog http ar io color os 使用 sp
原文地址:http://www.cnblogs.com/wuchanming/p/4172891.html