剑指Offer系列---(14)数值的整数次方
来源:互联网 发布:git ssh 非22端口 编辑:程序博客网 时间:2024/05/20 05:05
1.题目描述:
实现函数double Power(double base,int exponent),求base的exponent次方。不得使用库函数,同时不需要考虑大数问题。
2.源代码:
// Copyright (c) 2015年 skewrain. All rights reserved.#include <iostream>#include <stdio.h>using namespace std;//自以为题目简单的解法,不能处理负数和0。double Power1(double base,int exponent){ double result = 1.0; for (int i=1; i<=exponent; i++) { result *= base; } return result;}//全面但不够高效的解法,使用全局变量。bool g_InvalidInput = false;bool equal(double num1,double num2){ if((num1-num2 >-0.0000001)&&(num1-num2 <0.0000001)) return true; else return false;}double PowerWithUnsignedExponent1(double base,unsigned int exponent){ double result = 1.0; for (int i=1; i<=exponent; i++) { result *= base; } return result;}double Power2(double base,int exponent){ g_InvalidInput = false; if(equal(base, 0.0) && exponent <0) { g_InvalidInput = true; return 0.0; } unsigned int absExponent = (unsigned int)exponent; if (exponent < 0) { absExponent = (unsigned int)(-exponent); } double result = PowerWithUnsignedExponent1(base,absExponent); if (exponent < 0) { result = 1.0/result; } return result;}//全面而高效的解法double PowerWithUnsignedExponent2(double base,unsigned int exponent){ if (exponent == 0) return 1; if (exponent == 1) return base; //用右移运算符代替了除以2 double result = PowerWithUnsignedExponent2(base,exponent>>1); result *= result; //用位与运算符代替了求余运算符(%)来判断一个数是奇数还是偶数。 if((exponent & 0x1) == 1) result *= base; return result;}int main(int argc,char *argv[]){ int base,exponent; cout<<"请输入基数:"; cin>>base; cout<<"请输入指数:"; cin>>exponent; cout<<base<<"的"<<exponent<<"次方的值为:"<<Power1(base,exponent)<<endl; cout<<base<<"的"<<exponent<<"次方的值为:"<<Power2(base,exponent)<<endl; return 0;}
0 0
- 剑指Offer系列---(14)数值的整数次方
- 剑指offer系列源码-数值的整数次方
- 剑指offer系列之十一:数值的整数次方
- 【剑指offer系列】 数值的整数次方___11
- 剑指offer系列-T11数值的整数次方
- 剑指Offer系列-面试题11:数值的整数次方
- 【剑指offer-解题系列(12)】数值的整数次方
- 剑指Offer之数值的整数次方
- 剑指offer:数值的整数次方
- 【剑指offer】数值的整数次方
- [剑指offer]Q11:数值的整数次方
- 【剑指offer】数值的整数次方
- 剑指Offer之数值的整数次方
- 《剑指offer》数值的整数次方
- 剑指offer--数值的整数次方
- 剑指Offer之 - 数值的整数次方
- 剑指offer-11 数值的整数次方
- 剑指offer 11 - 数值的整数次方
- MySQL文件目录格式及存放位置
- HDU 5422 Rikka with Graph
- Text Justification
- 我的感想九
- String、StringBuffer与StringBuilder之间的区别
- 剑指Offer系列---(14)数值的整数次方
- 0909Android基础多线程编程
- Android的服务——Service和IntentService
- 零极限-《富在工作》摘要
- log日志记录是什么
- HashMap实现原理分析
- 关于MySql在调试过程中出现Driver not loaded Driver not loaded的问题的解决办法
- 九点领导力,用好非常受益
- thinkphp 异步=登陆+注册+注销 jquery+ajax+thinkphp