Sword refers to offer interview question 11, and sword refers to offer question 11

Source: Internet
Author: User

Sword refers to offer interview question 11, and sword refers to offer question 11

Question:
Implement the double Power (double base, int exponent) function to calculate the Power of base's exponent. Do not use library functions, and do not need to consider large numbers.

#include<iostream>using namespace std;double PowerUnsigned(double base ,unsigned int exponent){    if (exponent == 0)        return 1;    if (exponent == 1)        return base;    double result = PowerUnsigned(base,exponent>>1);    result *= result;    if ((exponent & 0x1) == 1)        result = result*base;    return result;}bool equal(double num1,double num2){    if ((num1 - num2 > -0.00000001) && (num1 - num2 < 0.00000001))        return true;    else        return false;}double Power(double base, int exponent){    if (equal(base, 0) && exponent < 0)        throw exception("Invaild value");    unsigned int absExponent = static_cast<unsigned int>(abs(exponent));    double result = PowerUnsigned(base, absExponent);    if (exponent < 0)        result = 1 / result;    return result;}int main(){    double v1 = 2;    int v2 = -1;    cout<<Power(v1,v2);    return 0;}

Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.