[LintCode] Pow(x, n) 求x的n次方

简介:

Implement pow(x, n).

 Notice

You don't need to care about the precision of your answer, it's acceptable if the expected answer and your answer 's difference is smaller than 1e-3.

Example
Pow(2.1, 3) = 9.261
Pow(0, 1) = 0
Pow(1, 0) = 1

LeetCode上的原题,请参见我之前的博客Pow(x, n)

解法一:

class Solution {
public:
    /**
     * @param x the base number
     * @param n the power number
     * @return the result
     */
    double myPow(double x, int n) {
        if (n == 0) return 1;
        double half = myPow(x, n / 2);
        if (n % 2 == 0) return half * half;
        else if (n > 0) return half * half * x;
        else return half * half / x;
    }
};

解法二:

class Solution {
public:
    /**
     * @param x the base number
     * @param n the power number
     * @return the result
     */
    double myPow(double x, int n) {
        if (n == 0) return 0;
        if (n == 1) return x;
        if (n == -1) return 1 / x;
        return myPow(x, n / 2) * myPow(x, n - n / 2);
    }
};

本文转自博客园Grandyang的博客,原文链接:求x的n次方[LintCode] Pow(x, n) ,如需转载请自行联系原博主。

相关文章
|
算法 安全 Swift
LeetCode - #50 Pow(x, n)
不积跬步,无以至千里;不积小流,无以成江海,Swift社区 伴你前行。如果大家有建议和意见欢迎在文末留言,我们会尽力满足大家的需求。
|
算法 API
leetcode:50.Pow(x, n)
实现 pow(x, n),即计算 x 的 n 次幂函数。
35 0
LeetCode:1. 两数之和 two-sum
LeetCode:1. 两数之和 two-sum
82 0
LeetCode 50. Pow(x, n)
实现pow(x,n),即计算x的n次方
66 0
LeetCode 50. Pow(x, n)
LeetCode tow Sum 两数之和
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。
69 0
LeetCode tow Sum 两数之和
求一个数n次方后的末尾数(数论/快速幂)
hdu1061-Rightmost Digit hdu1097-A hard puzzle 这两个oj题目思路几乎一样,都是为了快速求出一个数n次方后的末尾数为都多少?
193 0
求一个数n次方后的末尾数(数论/快速幂)
POJ-2389,Bull Math(大数乘法)
POJ-2389,Bull Math(大数乘法)
|
索引
LeetCode 1:两数之和 Two Sum
题目: 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。 你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
886 0
[LintCode] Two Sum 两数之和
Given an array of integers, find two numbers such that they add up to a specific target number. The function twoSum should return indices of the tw.
1346 0