• LeetCode 166. Fraction to Recurring Decimal


    原题链接在这里:https://leetcode.com/problems/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.

    Example 1:

    Input: numerator = 1, denominator = 2
    Output: "0.5"
    

    Example 2:

    Input: numerator = 2, denominator = 1
    Output: "2"

    Example 3:

    Input: numerator = 2, denominator = 3
    Output: "0.(6)"

    题解:

    加入整数部分后,在reminder 不为0的时候添加小数部分,用HashMap来维护reminder 和 对应的小数长度. 若是出现无限循环可以找到加左括号的起始点.

    AC Java:

     1 public class Solution {
     2     public String fractionToDecimal(int numerator, int denominator) {
     3         if(numerator == 0){
     4             return "0";
     5         }
     6         if(denominator == 0){
     7             return "";
     8         }
     9         
    10         StringBuilder res = new StringBuilder();
    11         long num = Math.abs((long)numerator);
    12         long deno = Math.abs((long)denominator);
    13         
    14         //如果是负数
    15         if((numerator < 0) ^ (denominator < 0)){
    16             res.append("-");
    17         }
    18         
    19         res.append(num/deno);
    20         long reminder = num%deno;
    21         if(reminder == 0){
    22             return res.toString();
    23         }
    24         
    25         //有小数
    26         res.append(".");
    27         //HashMap中计入reminder 和 对应的小数部分长度,用来找到循环开始的位置
    28         HashMap<Long, Integer> hm = new HashMap<Long, Integer>();
    29         StringBuilder desRes = new StringBuilder();
    30         while(reminder != 0){
    31             if(hm.containsKey(reminder)){ //出现了循环,找到循环开始的index添加左括号
    32                 int beginIndex = hm.get(reminder);
    33                 desRes.insert(beginIndex, "(");
    34                 desRes.append(")");
    35                 res.append(desRes);
    36                 return res.toString();
    37             }
    38             hm.put(reminder, desRes.length());
    39             desRes.append(reminder*10/deno);
    40             reminder = (reminder*10)%deno;
    41         }
    42         res.append(desRes);
    43         return res.toString();
    44     }
    45 }

    Decimal To Fraction 小数转换成分数类似.

  • 相关阅读:
    解决方案 git@github.com出现Permission denied (publickey)
    github设置添加SSH
    base64是啥原理
    PHP面试题:HTTP中POST、GET、PUT、DELETE方式的区别
    PHP中put和post区别
    常用的微信编辑器
    局域网内一台电脑的ip地址自己会变,怎样让它不变
    Trendalyzer is an information visualization software
    FineReport报表和水晶报表的比较
    x
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/4825053.html
Copyright © 2020-2023  润新知