练习:打表与边写边求

输入一个数,和一个数字,如34553 5,得到一个新的数字55(即将数字5抽离出来形成新数)。现输入两组求得到的两个新数的和。数的范围是0~10^10。

input: 
34545 3 45676 5
output:
8

法一:打表法,想找到需要的信息
要得到55,先要的到5,接着得到5出现的次数

#include <iostream>
#include <string>
#include <algorithm>

using namespace std;

class solution
{
public:
	solution(){}
	solution(string line) {
		resolve(line);
	    addP1andP2();
	}
	~solution(){}

	void resolve(string line) {
		int str1Length = getStr1Length(line);
		m_numberChar1 = line.at(str1Length +1);
		m_numberChar2 = line.back();
		times1 = 0;
		times2 = 0;
		for (int i = 0; i < str1Length; i++) {
			if (line.at(i) == m_numberChar1) times1++;
		}
		for (int i = str1Length+3; i < line.length()-2; i++) {
			if (line.at(i) == m_numberChar2) times2++;
		}
	}

	int getStr1Length(string &line) {
		int str1Length = 0;
		char ch = line.at(0);
		while (ch != ' ') {
			str1Length++;
			ch = line.at(str1Length);
		}
		return str1Length;
	}

	void addP1andP2() {
		int p1 = getPn(1);
		int p2 = getPn(2);
		cout<<p1 + p2<<endl;
	}

	int getPn(int type) {
		int Pn = 0;
		if (type == 1) {
			int num = m_numberChar1 - '0';
			for (int i = 0; i < times1; i++) {
				Pn = Pn * 10 + num;
			}
		}
		else if (type == 2) {
			int num = m_numberChar2 - '0';
			for (int i = 0; i < times2; i++) {
				Pn = Pn * 10 + num;
			}
		}
		else {
			cout << "type must be 1 or 2" << endl;
		}	
		return Pn;
	}
	
private:
	char m_numberChar1, m_numberChar2;
	int times1,times2;
};


int main()
{
	string line = "";
	getline(cin, line);
	solution  test(line);
	system("pause");
	return 0;
}

法二:边找边用,直接生成新数

#include <iostream>
#include <string>
#include <algorithm>

using namespace std;

long long getNewNumber(long long &old, long long &fig) {
	int newNumber = 0;
	while (old != 0) {
		int endFigure = old % 10;
		if (endFigure == fig) newNumber = newNumber * 10 + fig;
		old /= 10;
	}
	return newNumber;
}

int main()
{
	long long oldNumber1, figure1, oldNumber2, figure2;
	cin >> oldNumber1 >> figure1 >> oldNumber2 >> figure2;
	long long P1 = getNewNumber(oldNumber1, figure1);
	long long P2 = getNewNumber(oldNumber2, figure2);
	cout << P1 + P2 << endl;
	system("pause");
	return 0;
}

发布了27 篇原创文章 · 获赞 1 · 访问量 1423

猜你喜欢

转载自blog.csdn.net/qq_34890856/article/details/104007575
今日推荐