5.9 LeetCode

5.9 LeetCode

166. Fraction to Recurring Decimal

  1. 分数到小数
    给定两个整数,分别表示分数的分子 numerator 和分母 denominator,以字符串形式返回小数。
    如果小数部分为循环小数,则将循环的部分括在括号内。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
class Solution {
public String fractionToDecimal(int numerator, int denominator) {
long n=Math.abs((long)numerator),d=Math.abs((long)denominator);
StringBuilder sb=new StringBuilder();
if((long)numerator * (long)denominator < 0)
sb.append("-");
sb.append(String.valueOf(n/d));
n%=d;
if(n==0) return sb.toString();
sb.append(".");
int t=2;
while(t<n){
if((n/t)*t==n &&(d/t)*t==d)
{
n/=t;d/=t;
}
else t++;
}
//System.out.println(n+" "+d);
long index=sb.length();
HashMap<Long,Long> m=new HashMap<>();
while(n!=0){
if(m.containsKey(n)){
sb.insert(Integer.parseInt(m.get(n).toString()),"(");
sb.append(")");
break;
}
m.put(n,index);
n*=10;
sb.append(n/d);
n=n%d;
index++;
}
return sb.toString();

}

}

371. Sum of Two Integers

371.两整数之和
不使用运算符 + 和 - ​​​​​​​,计算两整数 ​​​​​​​a 、b ​​​​​​​之和。

1
2
3
4
5
class Solution {
public int getSum(int a, int b) {
return b == 0 ? a : getSum(a^b,(a&b)<<1);
}
}

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×