[剑指Offer]字符流中第一个不重复的字符--数组中重复的数--把字符串转换成整数--不用加减乘除做加法--求1+2+3+...+n

字符流中第一个不重复的字符

class Solution
{
public:
    int str[128];
    queue<char> myQueue;
  //Insert one char from stringstream
    void Insert(char ch)
    {
        str[ch-'\0']++;
        if(1==str[ch-'\0'])
        {
            myQueue.push(ch);
        }
    }
  //return the first appearence once char in current stringstream
    char FirstAppearingOnce()
    {
        while((!myQueue.empty()) && (str[myQueue.front()] > 1))
            myQueue.pop();       
        if (myQueue.empty()) 
            return '#';
        return myQueue.front();
    }
};

数组中重复的数

class Solution {
public:
    // Parameters:
    //        numbers:     an array of integers
    //        length:      the length of array numbers
    //        duplication: (Output) the duplicated number in the array number
    // Return value:       true if the input is valid, and there are some duplications in the array number
    //                     otherwise false
    bool duplicate(int numbers[], int length, int* duplication) {
        int arr[length];
        for(int i=0;i<length;i++) arr[i]=0;
        if(length<=1) return false;
        for(int i=0;i<length;i++)
        {
            arr[numbers[i]]++;
        }
        for(int i=0;i<length;i++)
        {
            if(arr[i]>1)
            {
                *duplication=i;
                return true;
            }
        }
        return false;
    }
};

把字符串转换成整数

class Solution {
public:
    int StrToInt(string str) {
		if (str == "")return 0;
		int num=0;
		int flag=1;
		cout << str.find_first_not_of("1234567890+-") << endl;
		if (str.find_first_not_of("1234567890+-") < str.size())  return 0;//如果存在不合法字符
		char ch = str[0];
		int i = 0;
		if (ch == '-') 
		{
			flag = 0;
			i = 1;
		}
		else if (ch == '+')
		{
			flag = 1;
			i = 1;
		}
		while (i<str.size())
		{
			int a = str[i]-'0';
			num = num * 10 + a;
			cout << "num:" << num << endl;
			i++;
		}
		if (flag == 0) num = -num;
		return num;
	}
};

不用加减乘除做加法

class Solution {
public:
    int Add(int num1, int num2)
    {
        if(num1==0) return num2;
        if(num2==0) return num1;
        int sum=0,carry=0;
        sum=num1^num2;
        carry=(num1&num2)<<1;
        return Add(sum,carry);
    }
};

求1+2+3+…+n

class Solution {
public:
    int Sum_Solution(int n) {
        return (1+n)*n/2;
    }
};

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