• [leedcode 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) {
              //注意正负
              //注意越界(转为long)
              //使用map记录余数和位置,当发现相同的余数时,则表示此余数对应位置的商位开始循环,此时需要用()包装
              //seq表示商
              long num=Math.abs((long)numerator);
              long deno=Math.abs((long)denominator);
              int flag=1;
              if(numerator>0&&denominator<0||numerator<0&&denominator>0) flag=0;
              long s=num/deno;
              long t=num%deno;
              String res=flag==0?"-"+Long.toString(s):Long.toString(s);
              if(t==0) return res;
              else return res+"."+getRes(t,deno);
              
          }
          public StringBuilder getRes(long t,long deno){
              StringBuilder seq=new StringBuilder();
              HashMap<Long,Integer> map=new HashMap<Long,Integer>();
              int i=0;
              while(t!=0&&!map.containsKey(t)){
                  map.put(t,i);
                  i++;
                  t*=10;
                  seq.append(Long.toString(t/deno));
                  t%=deno;
                  
              }
              if(t!=0){
                  seq.insert((int)map.get(t),'(');
                  seq.append(')');
              }
              return seq;
          }
      }
  • 相关阅读:
    opencv 遍历Mat对象中数据方法-转
    JVM OutOfMemoryError 分析
    hibernate validation HV000030: No validator could be found for constraint
    通过aop实现rpc统一参数校验&异常捕捉
    java8 lambda groupingby 分组保持原来顺序
    递归判断素组是否有序
    dubbo 直连
    Linux 删除openjdk
    telnet命令调用远程dubbo 接口
    git submodule ssh key
  • 原文地址:https://www.cnblogs.com/qiaomu/p/4695915.html
Copyright © 2020-2023  润新知