求1+2+..+n,不用加减乘除做加法,把字符串转换成整数,数组中重复的数字(剑指offer47-50)c++版本

#include 

using namespace std;

class Solution {
public:
	//JZ47 求1+2+3+...+n
	int Sum_Solution(int n);
	//JZ48 不用加减乘除做加法
	int Add(int num1, int num2);
	//JZ49 把字符串转换成整数
	int MAX_49 = 0;
	int StrToInt(string str);
	int ispositive(string str);
	int StrToIntCore(string str, int len, int index);
	//JZ50 数组中重复的数字
	bool duplicate(int numbers[], int length, int* duplication);
};

//JZ47 求1+2+3+...+n
int Solution::Sum_Solution(int n) {
	//短路求值原理
	int result = n;
	(n) && (result += Sum_Solution(n - 1));
	return result;
}
//JZ48 不用加减乘除做加法
int Solution::Add(int num1, int num2) {
	//先相加不做进位;再求出进位的位置。两者相加
	int sum = num1 ^ num2;//相加不做进位
	int carry = (num1 & num2) << 1;//进位就是两者按位与,再左移一位
	while (carry) {//当没有进位的时候停止
		int temp = sum;
		sum ^= carry;
		carry = (temp & carry) << 1;
	}
	return sum;
}
//JZ49 把字符串转换成整数
int Solution::StrToInt(string str) {
	int len = str.size();
	if (len == 0)	return 0;
	if (len == 1 && (str[0] < '0' || str[0] > '9')) {
		MAX_49 = 1;//非法的
		return 0;
	}
	int flag = ispositive(str);
	int result = 0;
	if (flag == 3) {
		result = StrToIntCore(str, len, 0);
	}
	else{
		result = StrToIntCore(str, len, 1);
		result = (flag > 1) ? (-result) : result;
	}
	return result;
}
int Solution::ispositive(string str) {
	//判断正负
	if (str[0] == '+')	return 1;
	if (str[0] == '-')	return 2;
	return 3;
}
int Solution::StrToIntCore(string str, int len, int index) {
	int result = 0;
	while (index < len) {
		if (str[index] < '0' || str[index] > '9') {
			MAX_49 = 1;
			return 0;
		}
		result = result * 10 + (str[index] - '0');
		if (result > INT_MAX) {
			MAX_49 = 2;//数据溢出
			return 0;
		}
		index++;
	}
	return result;
}
//JZ50 数组中重复的数字
bool Solution::duplicate(int numbers[], int length, int* duplication) {
	//由于数组中的数字的范围是0到n-1,则若存在重复的数字,经过调整后该数字所在的位置必定与其下标无法对应
	if (length == 0)	return false;
	int i = 0;
	while (i < length) {
		if (numbers[i] == i)	i++;
		else if (numbers[numbers[i]] == numbers[i]) {
			*duplication = numbers[i];
			return true;
		}
		else {
			swap(numbers[i], numbers[numbers[i]]);
		}
	}
	return false;
}

//JZ47 求1+2+3+...+n
void test1() {
	int n = 5;
	Solution s;
	cout << s.Sum_Solution(n);
	return;
}
//JZ48 不用加减乘除做加法
void test2() {
	Solution s;
	cout << s.Add(3, 3);
	return;
}
//JZ49 把字符串转换成整数
void test3() {
	string str = "-12345";
	Solution s;
	cout << s.StrToInt(str);
	return;
}
//JZ50 数组中重复的数字
void test4() {
	int numbers[7] = { 2,3,1,0,2,5,3 };
	int length = 7;
	int* duplication = new int(1);
	*duplication = -1;
	Solution s;
	cout << s.duplicate(numbers, length, duplication) << endl;
	cout << "重复的数字是:" << *duplication;
	return;
}

int main() {
	//test1();
	//test2();
	//test3();
	test4();
	system("pause");
	return 0;
}

你可能感兴趣的:(剑指offer,算法)