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)".
解题思路:
首先得到商的整数部分,余数部分不能整除则在余数后面加0。用一个vector保存每次相除后的余数,出现了相同的余数,则意味着有循环小数。
一个容易忽略的点是INT_MIN,即0x80000000,它的整数用int保存不了,需要转换格式为long long。
实现代码:
/***************************************************************************** * @COPYRIGHT NOTICE * @Copyright (c) 2015, 楚兴 * @All rights reserved * @Version : 1.0 * @Author : 楚兴 * @Date : 2015/2/6 19:57 * @Status : Accepted * @Runtime : 18 ms *****************************************************************************/ #include <iostream> #include <vector> #include <algorithm> using namespace std; class Solution { public: string fractionToDecimal(int numerator, int denominator) { if (denominator == 0) { return ""; //分母为0 } if (numerator == 0) { return "0"; //分子为0 } long long num = numerator; long long den = denominator; bool flag = false; if ((num > 0 && den < 0) ||(num < 0 && den > 0)) { flag = true; } num = num >= 0 ? num : -num; den = den > 0 ? den : - den; string str = ""; long long result = num / den; //商的整数部分 char res[11]; itoa(result,res); int len = strlen(res); str += res; long long n = num % den; if (!n) { if (flag) { str.insert(str.begin(),'-'); } return str; } str += '.'; vector<long long> tail; int index = -1; while(n) { tail.push_back(n); n *= 10; str += n / den + '0'; n %= den; index = find(tail,n); if (index != -1) { break; } } if (index != -1) { str.insert(str.begin() + index + len + 1, '('); str.push_back(')'); } if (flag) { str.insert(str.begin(),'-'); } return str; } int find(vector<long long> num, long long n) { for (int i = 0; i < num.size(); i++) { if (num[i] == n) { return i; } } return -1; } void itoa(long long n, char* ch) //n不为负 { char* temp = ch; if (n == 0) { *temp++ = '0'; *temp = '\0'; return; } while(n) { *temp++ = n % 10 + '0'; n /= 10; } *temp = '\0'; reverse(ch); } void reverse(char* ch) { char* start = ch; char* end = ch + strlen(ch) - 1; char c; while(start < end) { c = *start; *start++ = *end; *end-- = c; } } }; int main() { Solution s; cout<<s.fractionToDecimal(-2147483648, 1).c_str()<<endl; cout<<s.fractionToDecimal(-1,-2147483648).c_str()<<endl; cout<<s.fractionToDecimal(1,6).c_str()<<endl; cout<<s.fractionToDecimal(-6,-7).c_str()<<endl; system("pause"); }