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

    Analyse: Use hash to store the fractional and its corresponding position at result. If the fractional has occurred, the result is recurring; If the fractional is 0, return current result. 

    Runtime: 0ms.

     1 class Solution {
     2 public:
     3     string fractionToDecimal(int numerator, int denominator) {
     4         if(!numerator) return "0";
     5         
     6         string result;
     7         unordered_map<int, int> um;
     8         if(numerator < 0 ^ denominator < 0) result += '-';
     9         long long int nu = numerator, de = denominator;
    10         nu = abs(nu);
    11         de = abs(de);
    12         
    13         result += to_string(nu / de);
    14         long long int fractional = nu % de;
    15         if(!fractional) return result;
    16         result += ".";
    17         
    18         while(fractional) {
    19             // find if the fractional is in um
    20             if(um.find(fractional) != um.end()) {
    21                 result.insert(um[fractional], "(");
    22                 result += ")";
    23                 return result;
    24             }
    25             
    26             // push the fractional and its position in result into um
    27             um[fractional] = result.length();
    28             
    29             fractional *= 10;
    30             result += to_string(fractional / de);
    31             fractional %= de;
    32         }
    33         return result;
    34     }
    35 };
  • 相关阅读:
    mysql 权限问题
    触发器作用
    带有循环功能的存储过程
    带有条件判断的存储过程
    数据存储 三大范式-----------待续
    存储过程自 带条件判断的存储过程
    线程异步更新UI
    TextBox只能输入数字
    C#中无边框窗体移动或拖控件移动窗体
    classloader原理
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/5755266.html
Copyright © 2020-2023  润新知