7. Reverse Integer
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
这题的思路很简单,就是现将整数x的每一位数提取出来,之后倒序乘上10的对应次方然后相加,再判断是否越界就行。无论正负对计算结果没有影响。
参考代码如下:
class Solution {
public:
int reverse(int x) {
long long result = 0;
int length = 0;
int num[15];
while(x != 0) {
num[length++] = x % 10;
x /= 10;
}
for (int i = 0; i < length; i++) {
result += num[i] * pow(10, length - 1 - i);
if(result > INT_MAX || result < INT_MIN) {
result = 0;
break;
}
}
return (int)result;
}
};
再来看另外一道题
75、 Sort Colors
Given an array with n objects colored red, white or blue, sort them so that objects of the same color are adjacent, with the colors in the order red, white and blue.
Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.
Note:
You are not suppose to use the library’s sort function for this problem
这题的主要思路就是利用交换把值为0的object放到最左,把为值为2的object放到最右,剩下的中间的就是值为1的object了。
使用变量i记录值为0的objects的边界,也就是i往左的所有objects的颜色值都为0,用变量j记录值为1的objects的边界,也就是j往右的所有objects的颜色值都为1,最后变量now是当前检测的object的位置,从头开始直到遇到j,遇到颜色值为0的object与nums[i]交换,遇到颜色值为1的object与nums[j]交换,使得检查过的所有object里,值为0的全部交换至左端,值为2的全部交换至左端,而遇到1不交换使得now往左,到i之前的值都为1,所以若now指代的当前值值为0时,交换后now指代的值由0转为1,无需判断,故可以直接判断下一个值,而若now指代的当前值值为2,和j指代的object交换,而j指代的object的颜色值为未知数,所以这时now便不能移向下一个位置,需要继续判断交换后的当前位置。当循环结束时便能得到排好序的vector了,而时间复杂度为
O(n)
O
(
n
)
参考代码如下:
class Solution {
public:
void sortColors(vector<int>& nums) {
int temp;
int i = 0, j = nums.size() - 1;
int now = i;
while(now <= j) {
if(nums[now] == 0) {
temp = nums[now];
nums[now] = nums[i];
nums[i] = temp;
i++;
now++;
}
else if(nums[now] == 2) {
temp = nums[now];
nums[now] = nums[j];
nums[j] = temp;
j--;
}
else {
now++;
}
}
}
};