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

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

注意有很多地方关于long 和int的处理

比如赋值n, d判断是否应该是负数的时候

如果写成

long n = (long) numerator>0? numerator: -numerator;long d = (long) denominator>0? denominator:-denominator;

就会有错误,可能是numerator作为int太短,所以前面加负号出错

public class Solution {    public String fractionToDecimal(int numerator, int denominator) {        // 我觉得特别清晰受益的一个解法https://leetcode.com/discuss/27159/my-java-solution       // long n = Math.abs(numerator), d = Math.abs(denominator);// 可能是特别大的数不能这么写       long n = numerator;       long d = denominator;       n = n>0? n:-n;       d = d>0? d:-d;        // 不要忘了全部变正数                String s = Long.toString(n/d);        int index = 0;         HashMap
hm = new HashMap
(); n = n%d; if(n!=0) s += "."; index += s.length(); // current digit's position,//idx放在这里才会及时反映出,小数点后的位置 //不断乘以10求得小数点后的位数 while(n>0){ if(hm.get(n)==null) hm.put(n, index); else{ s = s.substring(0,hm.get(n)) + "(" + s.substring(hm.get(n),index) + ")"; break; } n *=10; s += Long.toString(n/d); n %= d; index++; } // if(numerator*denominator<0) s = "-"+s;// 可能是特别大的数不能这么写 if((numerator<0&&denominator>0) ||(numerator>0&& denominator<0)) s = "-"+s; return s; }}

 

转载于:https://www.cnblogs.com/jiajiaxingxing/p/4453124.html

你可能感兴趣的文章
4/25
查看>>
python3 第十七章 - sequence(序列)
查看>>
『cs231n』作业3问题3选讲_通过代码理解图像梯度
查看>>
关于新标签dialog
查看>>
最大正方形
查看>>
万径人踪灭(FFT+manacher)
查看>>
技术规格说明书
查看>>
图写成一个类(2)
查看>>
Segmentation fault (core dumped) 错误的一种解决场景
查看>>
hdu1150 Machine Schedule (匈牙利算法模版)
查看>>
惠普 hpssacli 工具使用
查看>>
Solr综合案例深入练习
查看>>
关于strcpy的实现.
查看>>
mysql新建表示,时间字段timetamp碰到的问题
查看>>
HDU - 2612 Find a way(BFS)
查看>>
Linux命令1
查看>>
debian 8 [jessie] 无线网卡驱动安装
查看>>
UML中的依赖,组合关系等+C#
查看>>
数据结构双向循环链表的C语言实现(插入,查询,删除)
查看>>
ubantu下用qemu搭建arm+linux运行环境
查看>>