题目描述
给定一个double类型的浮点数base和int类型的整数exponent。求base的exponent次方。
思路
-
当exponent位为偶数的时候
- 比如求2的100次方
- 2 ^ 100 = (2 ^2) ^ 50
- 即: x 的 exponent次方 = x * x的exponent/2次方
-
当exponent为奇数的时候
- 比如求2 的 101次方
- 2^101 = 2 * (2 ^ 100) = 2 * (2 ^ 2) ^ 50
- 即:x的exponent次方= x 乘以 x * x的exponent/2次方
class Solution {
public:
double Power(double base, int exponent) {
//求base^exponent
if(exponent == 0) return 1;
if(exponent < 0) base = 1/base;
exponent = abs(exponent);
if(exponent % 2 == 1)
return Power(base * base , exponent / 2) * base;
else return Power(base * base, exponent / 2);
}
};
题目描述
输入一个整数数组,实现一个函数来调整该数组中数字的顺序,使得所有的奇数位于数组的前半部分,所有的偶数位于数组的后半部分,并保证奇数和奇数,偶数和偶数之间的相对位置不变。
思路
- 首先i = - 1, j = 0
- 循环:
- 当array[j]为奇数的时候
- i + 1到j - 1之间的数据,整体往后移动一位
- i+1的数为以前array[j]的数
- 然后i++,j++
class Solution {
public:
void reOrderArray(vector<int> &array) {
if(array.size() <= 1) return;
int i = -1,j = 0;
while(j < array.size()){
//array[j]为奇数的时候
if(array[j] % 2 == 1){
int temp = array[j];
for(int k = j; k > i; k--)
array[k] = array[k - 1];
array[++i] = temp;
}
j++;
}
}
};