1. 程式人生 > 實用技巧 >Huawei機試系列(3)

Huawei機試系列(3)

提取不重複的整數

題目描述詳見提取不重複整數

這個題目可以reverse之後參照非排序去重,以下直接在原序列末尾操作。

#include <iostream>
#include<string>
using namespace std;

int main()
{
	string num;
	while (cin >> num)
	{
		int len = num.length(), index = len - 1;
		bool flag = true;
		for (int i = len - 1; i >= 0; --i)
		{
			for (int j = len - 1; j > index; --j)
			{
				if (num[i] == num[j])
				{
					flag = false;
					break;
				}
			}
			if (flag)
			{
				num[index] = num[i];
				--index;
			}
			else flag = true;
		}
		for (int i = len - 1; i > index; --i)
			cout << num[i];
		cout << endl;
	}
}

字串最後一個單詞長度

題目描述詳見字串最後一個單詞長度

這個題目難度是較難,我還以為有什麼坑,emm

#include <iostream>
#include<string>
#include<algorithm>
using namespace std;

int main()
{
	string str;
	while (getline(cin,str))
	{
		int count = 0;
		reverse(str.begin(), str.end());
		for (auto elem : str)
			if (elem == ' ')
				break;
			else
				++count;
		cout << count << endl;
	}
}

計算字元個數

題目描述詳見計算字元個數

注意不區分大小寫,所以有四種情況(大大,大小,小大,小小)

#include <iostream>
#include<string>
using namespace std;

int main()
{
	string str;
	while (cin >> str)
	{
		char ch;
		int count = 0;
		cin >> ch;
		for (auto elem : str)
			if (elem == ch || static_cast<char>(elem + 32) == ch || static_cast<char>(elem - 32) == ch)
				++count;
		cout << count << endl;
	}
}

字串分隔

問題描述詳見字串分隔

#include <iostream>
#include<string>
using namespace std;

int main()
{
	string str;
	while (cin >> str)
	{
		for (int i = 0; i < str.length(); ++i)
		{
			cout << str[i];
			if ((i + 1) % 8 == 0)
				cout << endl;
		}

		if (str.length() % 8 != 0)  //若長度不是8的倍數
		{
			for (int i = str.length() % 8; i < 8; ++i)
				cout << 0;
			cout << endl;
		}
	}
}

質數因子

題目描述詳見質數因子

若是知道質數序列可以省下很多不必要的比較

#include <iostream>
#include<string>
using namespace std;

int main()
{
	long num;
	int i = 2;
	while (cin >> num) {
		while (num != 1)
		{
			if (num % i == 0) //若是整除,輸出i,商替換num
			{
				cout << i << ' ';
				num /= i;
			}
			else  //不整除,i自增
				++i;
		}
	}
}