LeetCode - 50/69/367/633 - Pow(x, n)、Sqrt(x)

50. Pow(x, n)

Implement pow(xn).

简单粗暴的题目解释【笑哭】

用了快速幂,不过wa了一下,因为没考虑到int的最小值转化为正数后会爆掉。时间复杂度O(logn),空间复杂度O(1)

class Solution {
public:
    double myPow(double x, int n) {
        if (n == 0) return 1;
        long long m = abs((long)n);
        if (n < 0) {
            x = 1 / x;
        }
        double ans = 1;
        while (m > 0) {
            if (m & 1) ans *= x;
            x *= x;
            m >>= 1;
        }
        return ans;
    }
};




69. Sqrt(x)

Implement int sqrt(int x).

Compute and return the square root of x.

本来还想用sqrt(x)做下比较,可能脑子进水了吧。。。

时间复杂度O(logn),空间复杂度O(1)

class Solution {
public:
    int mySqrt(int x) {
        long long le = 0, ri = (long long)x + 1;
        while (le < ri - 1) {
            long long mid = (le + ri) >> 1;
            if (mid * mid > x) ri = mid;
            else le = mid;
        }
        return le;
    }
};




367. Valid Perfect Square

Given a positive integer num, write a function which returns True if num is a perfect square else False.

Note: Do not use any built-in library function such as sqrt.

Example 1:

Input: 16
Returns: True

Example 2:

Input: 14
Returns: False

相当于69题换了个描述方法,本质还是实现sqrt(x)

时间复杂度O(logn),空间复杂度O(1)

class Solution {
public:
    bool isPerfectSquare(int num) {
        long long le = 0, ri = (long long)num + 1;
        while (le < ri - 1) {
            long long mid = (le + ri) >> 1;
            if (mid * mid > num) ri = mid;
            else le = mid;
        }
        if (le * le == (long long)num) return true;
        return false;
    }
};




633. Sum of Square Numbers

Given a non-negative integer c, your task is to decide whether there're two integers a and b such that a2 + b2 = c.

Example 1:

Input: 5
Output: True
Explanation: 1 * 1 + 2 * 2 = 5

Example 2:

Input: 3
Output: False

判断一个数能不能拆成两个平方和。

时间复杂度O(n),空间复杂度O(1)

class Solution {
public:
    bool judgeSquareSum(int c) {
        int le = 0, ri = sqrt(c);
        while (le <= ri) {
            if (le * le + ri * ri == c) return true;
            else if (le * le + ri * ri > c) ri--;
            else le++;
        }
        return false;
    }
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值