leetcode:Fraction to Recurring Decimal
2015-10-07 11:18
483 查看
原题如下:
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)”.
原题地址:https://leetcode.com/problems/fraction-to-recurring-decimal/
需要注意的地方:
1、溢出,可观察如下输出结果,一定在使用a之前强制转换。
2、分数都是有理数,都是有限小数或者无限循环小数
3、String vs StringBuilder
下面是代码:
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)”.
原题地址:https://leetcode.com/problems/fraction-to-recurring-decimal/
需要注意的地方:
1、溢出,可观察如下输出结果,一定在使用a之前强制转换。
int a = -2147483648; long a1 = Math.abs(a); //输出 -2147483648 long a2 = Math.abs((long)a); //输出 2147483648
2、分数都是有理数,都是有限小数或者无限循环小数
3、String vs StringBuilder
下面是代码:
import java.util.HashMap; public class Solution{ //解这个题需要注意:分数一定是有理数,即分数转化为小数时一定是有限小数或者无限循环小数 //理解String与StringBuilder的区别,String是字符串常量,每次操作都是建一个新的变量,而StringBuilder是字符串变量 public String fractionToDecimal(int numerator, int denominator) { StringBuilder res = new StringBuilder(); long zi = Math.abs((long)numerator),mu = Math.abs((long)denominator); //判断符号 if(!(numerator<0==denominator<0) && numerator !=0){ res.append("-"); } long reminder = zi%mu; long divide = zi/mu; if(reminder==0){ //能除尽,不产生小数 res.append(divide); return res.toString(); } res.append(divide); res.append("."); //下面开始计算小数,一旦出现相同的小数,即出现循环 //用map记录小数的位置,只有第一个小数的位置有用 //注意:当余数不为零的时候,除法运算就是不断将余数乘以10,然后再求除数与余数,不断循环的过程 //所以一旦出现相同的余数,那么就是一个循环 HashMap<Long,Integer> map = new HashMap<Long,Integer>(); while(!map.containsKey(reminder)){ map.put(reminder, res.length()); res.append(10*reminder/mu); reminder = 10*reminder%mu; } int index = map.get(reminder); res.insert(index, "("); res.append(")"); return res.toString().replace("(0)", ""); } public static void main(String[] args) { Solution s = new Solution(); System.out.println(s.fractionToDecimal(-1, -2147483648)); } }
相关文章推荐
- MySql数据库索引原理(总结性)
- latex建立参考文献的超链接 生成书签
- mysql(创建存储过程和函数.2)
- Missing Number
- (转)MySql数据库索引原理(总结性)
- 安装CentOS-6.7
- Android:android:listSelector="#00000000" 与 android:listSelector="@null"之区别
- NppAStyle-0.2.0-20151006 is out
- SQL表两列取一列唯一值的记录
- 文章标题
- c++ primer 第四章习题(2)
- [DB][MyBatis]利用mybatis-paginator实现分页(目前看到MyBatis下最好的分页实现)
- poj 3254 Corn Fields (状压DP)
- Android属性动画
- position:absolute相对于谁定位以及当溢出时怎么隐藏
- mysql(存储过程和函数)
- swift中的as?和as!
- Cocos2dx编译Android问题之Multiple markers at this line
- Mybatis分页和Spring的集成
- Ubuntu 将正式支持 ZFS 文件系统