题意:
解题思路:
思路:模拟除法过程
PHP代码实现:
class Solution {
/**
* @param Integer $numerator
* @param Integer $denominator
* @return String
*/
function fractionToDecimal($numerator, $denominator) {
if ($denominator == 0) return "0";
$ans = "";
if (($numerator < 0 && $denominator > 0)
|| ($numerator > 0 && $denominator < 0)) {
$ans = "-";
}
$n = abs($numerator);
$d = abs($denominator);
$ans .= floor($n / $d);
$mod = $n % $d;
if ($mod == 0) return $ans;
$ans .= ".";
$map = [];
while ($mod != 0) {
if (isset($map[$mod])) {
$ans = substr_replace($ans, "(", $map[$mod], 0);
$ans .= ")";
break;
}
$map[$mod] = strlen($ans);
$mod *= 10;
$ans .= floor($mod / $d);
$mod %= $d;
}
return $ans;
}
}
GO代码实现:
func fractionToDecimal(numerator int, denominator int) string {
if denominator == 0 {return ""}
var ans string
if numerator * denominator < 0 {
ans += "-"
}
n, d := ABS(numerator), ABS(denominator)
ans += strconv.Itoa(n / d)
mod := n % d
if mod == 0 {return ans}
ans += "."
hm := make(map[int]int)
rptPos := -1
for (mod != 0) {
if pos, ok := hm[mod]; ok {
rptPos = pos
break
}
hm[mod] = len(ans)
mod *= 10
ans += strconv.Itoa(mod / d)
mod %= d
}
if rptPos == -1 {
return ans
}
return fmt.Sprintf("%s(%s)", ans[:rptPos], ans[rptPos:])
}
func ABS(v int ) int {
if v < 0 {return -v}
return v
}