leetcode 50 值得再看一遍
2017-09-27 19:16
316 查看
写这个只适用于自己再次回顾的时候,方便查找
Implement pow(x, n).
首先int的最小值是- ....48 而int的最大值是47 这个就意味着-..48的绝对值越界了,但是math.abs中负数最大值的绝对值还是负数,因此我考虑到相似可以用到-..46不能是-..47因为这样数字的符号方向就可能变了。还有就是int的最大值和最小值可以通过Integer.MAX_VALUE和Integer.MIN_VALUE获得。这些都是细节,技巧在于return值和迭代。默认返回值是0.0
public double myPow(double x, int n) {
double y=x;
if(n==0){
return 1;
}else{
if(n==Integer.MIN_VALUE){
n=n+2;
}
int abs=Math.abs(n);
double temp=myPow(y,abs/2);
if(abs%2==0){
y=temp*temp;
}else{
y*=(temp*temp);
}
return n < 0 ? Math.max(1/y, 0.0):y;
}
}
Implement pow(x, n).
首先int的最小值是- ....48 而int的最大值是47 这个就意味着-..48的绝对值越界了,但是math.abs中负数最大值的绝对值还是负数,因此我考虑到相似可以用到-..46不能是-..47因为这样数字的符号方向就可能变了。还有就是int的最大值和最小值可以通过Integer.MAX_VALUE和Integer.MIN_VALUE获得。这些都是细节,技巧在于return值和迭代。默认返回值是0.0
public double myPow(double x, int n) {
double y=x;
if(n==0){
return 1;
}else{
if(n==Integer.MIN_VALUE){
n=n+2;
}
int abs=Math.abs(n);
double temp=myPow(y,abs/2);
if(abs%2==0){
y=temp*temp;
}else{
y*=(temp*temp);
}
return n < 0 ? Math.max(1/y, 0.0):y;
}
}
相关文章推荐
- 【LeetCode131-140】切割回文(值得再看一遍DP),切割词汇(需要看看,DP)
- Sort Colors [leetcode] 扫描数组一遍,O(1)空间复杂度的解法
- leetcode50-Pow(x, n)(实现浮点数的幂运算)
- Leetcode-50: Pow(x,n)
- LeetCode 50 Pow(x, n)
- 50 多个值得跟随的flash界人物
- 把LeetCode刷一遍
- LeetCode---(50)Pow(x, n)
- LeetCode - 50/69/367/633 - Pow(x, n)、Sqrt(x)
- LeetCode50 Pow(x, n)
- LeetCode(50) Pow(x, n)
- leetcode——50——Pow(x, n)
- LeetCode 50 Pow(x, n)
- leetcode_434. Number of Segments in a String 计算字符串中段的个数,只需遍历一遍字符串
- [Leetcode ??] 50 Pow(x, n)
- 50 多个值得跟随的flash界人物
- Leetcode 50 - Pow(x, n)
- leetcode 50 Implement Pow(x, n)
- leetcode || 50、Pow(x, n)
- [Leetcode] 50, 55, 45