zoukankan      html  css  js  c++  java
  • 【leetcode】Fraction to Recurring Decimal

    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)".

     

        0.16  
    6 ) 1.00
        0 
        1 0       <-- Remainder=1, mark 1 as seen at position=0.
        - 6 
          40      <-- Remainder=4, mark 4 as seen at position=1.
        - 36 
           4      <-- Remainder=4 was seen before at position=1, so the fractional part which is 16 starts repeating at position=1 => 1(6).

    如果发现余数曾经出现过,则说明开始循环了,利用一个hash表记录余数出现的位置即可
    注意INT_MIN转换成正数会溢出,故需要先把数字先转为long long int
    注意余数也要去long long int,因为-1,2147483648这种情况下,余数在计算乘以10的过程中会溢出
     
     1 class Solution {
     2 public:
     3     string fractionToDecimal(int numerator, int denominator) {
     4        
     5        
     6         string ans="";
     7         if(numerator==0) return "0";
     8        
     9         long long int n=numerator;
    10         long long int d=denominator;
    11         n=abs(n);
    12         d=abs(d);
    13        
    14         if(numerator<0^denominator<0) ans.push_back('-');
    15        
    16         map<long long int,int> hash;
    17        
    18         ans+=to_string(n/d);
    19         long long int rem=n%d;
    20         if(rem!=0) ans.push_back('.');
    21        
    22         while(rem!=0)
    23         {
    24             if(hash.find(rem)!=hash.end())
    25             {
    26                 ans.insert(hash[rem],"(");
    27                 ans.push_back(')');
    28                 break;
    29             }
    30            
    31             hash[rem]=ans.length();
    32            
    33             ans+=to_string(rem*10/d);
    34             rem=(rem*10)%d;
    35         }
    36        
    37         return ans;
    38     }
    39 };
  • 相关阅读:
    ASP.NET26 个常用性能优化方法
    git 合并 二进制文件
    git 状态管理
    git 分支管理,提交到远程服务器上面
    git 发布android 系统版本 修改版本型号 查看指定文件的修改记录
    使用git 发布android系统版本 1
    提取文本当中的汉字
    wpf 命名空间中不存在
    c# 调用c DLL 所传参数不正确
    用于主题检测的临时日志(233d1263-3c3c-43d0-a2fd-318ee6fd58db
  • 原文地址:https://www.cnblogs.com/reachteam/p/4232228.html
Copyright © 2011-2022 走看看