【LeetCode】数学题
来源:互联网 发布:python 验证码识别库 编辑:程序博客网 时间:2024/06/09 04:28
50. Pow(x, n)
题目:实现幂函数
思路:递归——注意超出最大值的判断
public class Solution { public double myPow(double x, int n) { if(n < 0){ x = 1/x; n = ~n+1; } if(n == 0) return 1; if(n == 1) return x; if(x*x > Double.MAX_VALUE){ return 0.0; } if(n%2 == 0){ return myPow(x*x, n/2); } else{ return myPow(x*x, n/2)*x; } }}
69. Sqrt(x)
题目:实现开方函数
思路:二分——注意使用乘法,不要用除法,这样不会溢出。并且要求返回下取整。
public class Solution { public int mySqrt(int x) { if(x == 0) return 0; if(x == 1) return 1; int start = 0, end = x; while(start <= end){ int mid = start+(end-start)/2; if(mid == x/mid) return mid; else if(mid < x/mid){ start = mid+1; } else{ end = mid-1; } } return end; }}
367. Valid Perfect Square
题目:判断一个整数是不是完全平方数
思路:二分法——注意要强制转换为浮点型
public class Solution { public boolean isPerfectSquare(int num) { int start = 0, end = num; while(start <= end){ int mid = start + (end - start)/2; if((double)mid == (double)num/mid) return true; else if((double)mid > (double)num/mid){ end = mid - 1; } else{ start = mid + 1; } } return false; }}
还有一种牛顿方法
public boolean isPerfectSquare(int num) { long x = num; while (x * x > num) { x = (x + num / x) >> 1; } return x * x == num; }
阅读全文
0 0
- 数学题-leetcode
- 【LeetCode】数学题
- leetcode -- Gray Code -- 数学题
- 数学题
- 数学题
- 数学题
- 数学题
- 数学题
- 数学题
- 数学题
- 数学题
- 数学题
- 数学题
- 数学题
- 数学题
- 数学题
- 数学题
- 数学题
- Proxy SwitchySharp使用
- 文本三剑客之sed
- 格式与布局
- Harris 角点检测原理详解
- Linux驱动之Kobject、Kset (二)uevent mdev ktype type
- 【LeetCode】数学题
- tf.train.exponential_decay的用法
- OpenSSL命令详解
- MPAndroidChart 雷达图、饼图、气泡图、散点图、柱状图用法大全
- 《TCP/IP详解 卷1:协议》 读书笔记 第九章 IP选路
- LeetCode No.3 Longest Substring Without Repeating Characters
- Spring入门和基本操作
- Linux 设备总线驱动模型
- 发明大多源于模拟1——神经元