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

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

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)".
Java代码:

public class Solution {    public static String fractionToDecimal(int numerator, int denominator) {    String res = "";    long a = Math.abs((long) numerator);    long b = Math.abs((long) denominator);    if ((denominator < 0 && numerator > 0) || (denominator > 0 && numerator < 0)) {        res += "-";    }    long intPart= a / b;    res += intPart;    if (a % b == 0) {        return res;    }    res += ".";    long remainder = a % b;    HashMap
map = new HashMap
(); int i = 1; map.put(remainder, 1); Queue
queue = new LinkedList
(); int begin = -1; while (remainder != 0) { i++; long tmp = remainder * 10 / b; remainder = remainder * 10 % b; if (map.containsKey(remainder)) { begin = map.get(remainder); queue.offer(tmp); break; } else { map.put(remainder, i); queue.offer(tmp); } } if (remainder == 0) { while (!queue.isEmpty()) { res += queue.poll(); } } else { int j = 1; while (!queue.isEmpty()) { long cur = queue.poll(); if (j != begin) { res += cur; } else { res = res + "(" + cur; } j++; } res += ")"; } return res;}}
 

转载地址:http://qnuni.baihongyu.com/

你可能感兴趣的文章
Android自定义View实现商品评价星星评分控件
查看>>
postgresql监控工具pgstatspack的安装及使用
查看>>
postgresql查看表的和索引的情况,判断是否膨胀
查看>>
postgresql中根据oid和filenode去找表的物理文件的位置
查看>>
postgresql减少wal日志生成量的方法
查看>>
swift中单例的创建及销毁
查看>>
获取App Store中App的ipa包
查看>>
iOS 关于pods-frameworks.sh:permission denied报错的解决
查看>>
设置RGBColor
查看>>
设置tabbaritem的title的颜色及按钮图片
查看>>
动态设置label的高度
查看>>
获取 一个文件 在沙盒Library/Caches/ 目录下的路径
查看>>
图片压缩
查看>>
检测缓存文件是否超时
查看>>
十进制字符串转十六进制字符串
查看>>
属性字符串(富文本)的使用
查看>>
cell上label的背景颜色在选中状态下改变的解决办法
查看>>
GPS定位
查看>>
地图、显示用户位置、大头针
查看>>
自定义大头针
查看>>