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

    Hint:

    1. No scary math, just apply elementary math knowledge. Still remember how to perform a long division?
    2. Try a long division on 4/9, the repeating part is obvious. Now try 4/333. Do you see a pattern?
    3. Be wary of edge cases! List out as many test cases as you can think of and test your code thoroughly.

    本题之所以AC率如此的低是因为有很多的陷阱:int要转换成long型,并且要先转换再绝对值。思路是这样的,创建一个StringBuilder,然后判断符号,如果为负数,则把“-”输入到动态字符串里面,然后让被除数除以除数,商输入到动态字符串里面,检测余数,如果余数为0,则返回,否则,创建一个hashmap,用来存储余数,进入循环,将余数*10/除数存到动态字符串里面,看其余数,如果余数在hashmap里面出现,则说明是循环的,加入括号;否则,map里面加入余数;代码如下:

     1 public class Solution {
     2     public String fractionToDecimal(int numerator, int denominator) {
     3         if(numerator==0) return "0";
     4         long num = Math.abs((long)numerator);
     5         long den = Math.abs((long)denominator);
     6         StringBuilder sb = new StringBuilder();
     7         sb.append((numerator>0)^(denominator>0)?"-":"");
     8         sb.append(num/den);
     9         num = num%den;
    10         if(num==0) return sb.toString();
    11         sb.append(".");
    12         Map<Long,Integer> map = new HashMap<Long,Integer>();
    13         map.put(num,sb.length());
    14         while(num!=0){
    15             num = num*10;
    16             sb.append(num/den);
    17             num = num%den;
    18             if(map.containsKey(num)){
    19                 int index = map.get(num);
    20                 sb.insert(index,"(");
    21                 sb.append(")");
    22                 break;
    23             }
    24             map.put(num,sb.length());
    25         }
    26         return sb.toString();
    27     }
    28 }
  • 相关阅读:
    机器学习知识体系
    Request
    Http协议
    Servlet 学习
    Tomcat 服务器
    XML文件
    StringJdbc :jdbcTemplate
    Druid 数据库连接池
    c3p0配置文件(c3p0.properties.xml)解读
    数据库连接池 C3p0
  • 原文地址:https://www.cnblogs.com/codeskiller/p/6599230.html
Copyright © 2011-2022 走看看