zoukankan      html  css  js  c++  java
  • LeetCode 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)".

    Credits:
    Special thanks to @Shangrila for adding this problem and creating all test cases.

     1 public class Solution {
     2     public String fractionToDecimal(int numerator, int denominator) {
     3         if (numerator==0) {
     4             return "0";
     5         }
     6         String result="";
     7         if (numerator<0 ^ denominator<0) {
     8             result+="-";
     9         }
    10         long n=numerator;
    11         long d=denominator;
    12         n=Math.abs(n);
    13         d=Math.abs(d);
    14         long r=n%d;
    15         result+=n/d;
    16         if (r==0) {
    17             return result;
    18         }else {
    19             result+=".";
    20         }
    21         HashMap<Long, Integer> map=new HashMap<>();
    22         while (r>0) {
    23             if (map.containsKey(r)) {
    24 
    25                 result=result.substring(0, map.get(r))+"("+result.substring(map.get(r))+")";
    26                 return result;
    27             }else {
    28                 map.put(r, result.length());
    29                 r*=10;
    30                 result+=r/d;
    31                 r=r%d;    
    32             }
    33         }
    34         return result;
    35     }
    36 }
  • 相关阅读:
    运算符
    数据类型
    试题汇总
    文件读写
    Python操作
    字符串常用函数 void
    向量叉乘求任意多边形面积,凹凸均可 void
    约瑟夫问题各种求解办法 void
    大数类相关计算(c语言版) void
    求解一元多次方程(迭代法) void
  • 原文地址:https://www.cnblogs.com/birdhack/p/4179114.html
Copyright © 2011-2022 走看看