博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode Fraction to Recurring Decimal
阅读量:4627 次
发布时间:2019-06-09

本文共 1504 字,大约阅读时间需要 5 分钟。

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  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
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 }

 

转载于:https://www.cnblogs.com/birdhack/p/4179114.html

你可能感兴趣的文章
数据结构 - 主席树
查看>>
Linux——下常用程序的代理服务器(proxy)配置
查看>>
初步接触LVS
查看>>
Linux——Ubuntu下Sublime Text 2的安装
查看>>
Windows Store App 网络通信 HttpClient
查看>>
Win10系列:C#应用控件进阶5
查看>>
POJ 2828 Buy Tickets 线段树
查看>>
PHP导出csv文件
查看>>
iOS 打包ipa 教程
查看>>
LeetCode算法题--刷题第一天
查看>>
java操作word
查看>>
JavaScript对象创建
查看>>
加法变乘法|2015年蓝桥杯B组题解析第六题-fishers
查看>>
树状数组|求逆序数
查看>>
ALGO-141_蓝桥杯_算法训练_P1102
查看>>
如何跳转一个由两个框架组成的页面
查看>>
前端开发框架简介:angular和react
查看>>
MySQL安装图文教程
查看>>
Spring Aop基础总结
查看>>
架构设计:负载均衡层设计方案(2)——Nginx安装
查看>>