• 166. Fraction to Recurring Decimal


    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)".
    public class Solution {
        public String fractionToDecimal(int numerator, int denominator) {
            if(numerator == 0 || denominator == 0) return "0";
            String sign = "";
            if(numerator > 0 && denominator < 0 || numerator < 0 && denominator > 0) sign = "-";
            long num = Math.abs((long) numerator);
            long den = Math.abs((long) denominator);
            long major = num / den;
            long rem = num % den;
            if(rem == 0) return sign + major;
            
            StringBuilder sb = new StringBuilder(sign + major + ".");
            HashMap<Long, Integer> map = new HashMap<>();  // long : rem  integer 在sb中的pos
            while(rem != 0){
                if(map.containsKey(rem)){    //相同的余数, 循环开始
                    int index = map.get(rem);
                    sb.insert(index -1 , "(").append(")");  //因为sb中已经包含的循环部分;所以直接插入()
                    break;
                }
                else{
                   sb.append(rem * 10 / den);
                   map.put((rem) % den , sb.length());
                }
                rem =rem * 10 % den;
            }
            return sb.toString();
        }
    }
  • 相关阅读:
    WIN10下搭建reactnative开发Android环境
    node使用JsonWebToken 生成token,完成用户登录、登录检测
    SAP 学习网站汇总
    HTML5 学习网站收集
    优化 优化网站设计
    IoC容器 Spring.NET
    ORACLE 简介及安装
    MVC PureMVC
    HTML5 概要认识
    知识点 NHibernate
  • 原文地址:https://www.cnblogs.com/joannacode/p/6132887.html
Copyright © 2020-2023  润新知