Pow(x, n)
Thought:
1. Do it by loop.
2. Divide and conqueror, so the number of multiplications is reduced by half.
Solution:
- class Solution {
- public:
- double pow_proc(double x, int n) {
- double p;
- switch(n)
- {
- case 0:
- return 1;
- case 1:
- return x;
- default:
- p=pow_proc(x, n/2);
- if ((n & 1) == 0)
- return p*p;
- else
- return p*p*x;
- }
- }
- double pow(double x, int n)
- {
- if (n < 0)
- return 1.0/pow_proc(x, -n);
- else
- return pow_proc(x, n);
- }
- };
No comments:
Post a Comment