leetcode刷题笔记一百六十六题 分数到小数

leetcode刷题笔记一百六十六题 分数到小数

源地址:166. 分数到小数

问题描述:

给定两个整数,分别表示分数的分子 numerator 和分母 denominator,以字符串形式返回小数。

如果小数部分为循环小数,则将循环的部分括在括号内。

示例 1:

输入: numerator = 1, denominator = 2
输出: "0.5"
示例 2:

输入: numerator = 2, denominator = 1
输出: "2"
示例 3:

输入: numerator = 2, denominator = 3
输出: "0.(6)"

//基于一些数学原理处理 细节需要考虑较多
import scala.collection.mutable
object Solution {
    def fractionToDecimal(numberator: Int, denominator: Int): String = {
        val sb = new mutable.StringBuilder()
        
        if (numberator == 0) return "0"
        if ((numberator >= 0) ^ (denominator >= 0)) sb += '-'
        
        var num = math.abs(numberator.toLong)
        var denom = math.abs(denominator.toLong)
        var remaining = num % denom
        sb.append(num/denom)
        
        //除法运算结束
        if (remaining == 0) return sb.toString
        else{
            //进行小数部分处理
            remaining = remaining * 10
            sb += '.'
            //设计hashmap标记循环小数
            val map = mutable.HashMap[(Long, Long), Int]()
            
            while (remaining > 0) {
                val digit = remaining / denom
                remaining = remaining % denom
                
                if (map.contains((digit, remaining))){
                    val index = map((digit, remaining))
                    sb.insert(index, '(')
                    sb += ')'
                    return sb.toString
                }
                else{
                    sb.append(digit)
                    map.put((digit, remaining), sb.size-1)
                    remaining = remaining * 10
                }
            }
            return sb.toString
        }
    }
}
posted @ 2020-09-05 17:56  ganshuoos  阅读(159)  评论(0编辑  收藏  举报