数据结构练习(33)数值的整数次方
http://zhedahht.blog.163.com/blog/static/254111742009101563242535/
思路:
见过斐波那契,然后这题直接想到了递归2分法求解。
方法一还是蛮不错的,利用了位运算。不过代码写起来比较冗长。
#include <iostream> #include <bitset> using namespace std; double PowerWithExponent_1(double base, size_t exp) { bitset<32> bits(exp); if (bits.none()) return 1.0; double b[32]; for (int i = 0; i < 32; ++i) b[i] = 1.0; double power = 1.0; size_t cnt = 0; for (int i = 0; i < 32 && cnt <= bits.count(); ++i) { if (i == 0) power = base; else power *= power; if (bits.at(i)) b[i] = power, ++cnt; } power = 1.0; for (int i = 0; i < 32; ++i) if (bits.at(i)) power *= b[i]; return power; } double PowerWithExponentRecursively(double base, unsigned int exp) { if (exp == 0) return 1.0; double power = PowerWithExponentRecursively(base, exp >> 1); power *= power; if (exp & 0x01) power *= base; return power; } int main() { double power1 = PowerWithExponent_1(2.3, 3); double power2 = PowerWithExponentRecursively(2.3, 3); cout << power1 << " " << power2 << endl; return 0; }
-------------------------------------------------------
kedebug
Department of Computer Science and Engineering,
Shanghai Jiao Tong University
E-mail: kedebug0@gmail.com
GitHub: http://github.com/kedebug
-------------------------------------------------------