LeetCode算法题之一
题目描述:
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)".
刚看到题一脸蒙蔽,毕竟代码小白。
题目要求:给定两个整数 n, d 分别代表一个分数的分子和分母,求该分数的小数形式。如果该小数有循环部分,需要用括号将循环部分括起来。
在分析之后,感觉对于我来说还是有点难度的哈哈哈哈,此处借鉴了一下别人的思路,在对小数循环部分这块的判断,我们选择用哈希表来判断循环出现的位置。
这块贴一下相关代码:
public class DIVIDE {
public static String solution(int numerator,int denominator) {
long n = numerator;
long d = denominator;
if(n == 0 || d == 0)
return "0";
StringBuilder result = new StringBuilder();
if(n*d < 0)
result.append("-");
else
result.append(" ");
//取绝对值
n = Math.abs(n);
d = Math.abs(d);
//取余
result.append(n/d);
n = n % d;
//当可以整除时,直接返回
if(n == 0) return result.toString();
else result.append(".");
//定义一个哈希表
HashMap<Long,Integer> hashmap = new HashMap<Long,Integer>();
hashmap.put(n,result.length());
//计算小数部分
while(n != 0) {
n = n * 10;
result.append(n/d);
n = n % d;
if(hashmap.containsKey(n)) {
result.insert(hashmap.get(n), "(");
result.append(")");
break;
}
hashmap.put(n, result.length());
}
return result.toString();
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b = sc.nextInt();
DIVIDE d = new DIVIDE();
String h = d.solution(a, b);
System.out.println(h);
}
}
在这道题中,我们先是对分子为0或分母为0的情况进行了分析,然后进行了正负数的判断,如果是两个数符号相异,则要在结果前面加一个“-”(负号)。然后这时候对两个数都取绝对值,来进行计算,先算小数点前面的数,在计算小数点后面的数,然后返回结果。
在这块用到了hashmap的一些基本方法,来判断循环出现的位置。
文章前面算法部分有借鉴别人的思路啊-.-博主自己想不出来的嘤嘤嘤