【C++】算法笔记-第三章入门模拟

图形输出

在这里插入图片描述

//图形输出
#include<iostream>
using namespace std;
int main()
{
	int N; cin >> N;
	char ch; cin >> ch;
	//输出第一行
	for (int i = 0; i < N; i++) cout << ch;
	cout << endl;
	//输出第2~n-1行
	for (int i = 1; i < N - 1; i++)
	{
		cout << ch;
		for (int j = 1; j < N - 1; j++) cout << " ";
		cout << ch;
		cout << endl;
	}
	//输出第n行
	for (int j = 0; j < N; j++) cout << ch;
	cout << endl;
	return 0;
}

日期处理

在这里插入图片描述

//日期处理
#include<iostream>
using namespace std;

bool isLeap(int year)
{
	return ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0);
}

int main()
{
	int month[13][2] = { {0,0},{31,31},{28,29},{31,31},{30,30},{31,31} ,{30,30} ,
	{31,31} ,{31,31} ,{30,30} ,{31,31},{30,30} ,{31,31} };
	int time1, y1, m1, d1;
	int time2, y2, m2, d2;
	int days = 0;
	cin >> time1 >> time2;
	y1 = time1 / 1000; m1 = time1 % 1000 / 100; d1 = time1 % 100;
	y2 = time2 / 1000; m2 = time2 % 1000 / 100; d2 = time2 % 100;
	//快速计算跨多年情况
	for (int i = y1; i < y2; i++)//y1<y2
	{
		if (isLeap(i)) days += 366;
		else days += 365;
	}
	while (!(y1 == y2 && m1 == m2 && d1 == d2))
	{
		d1++;
		if (d1 > month[m1][isLeap(y1)])//满月,日改为1
		{
			m1++;
			d1 = 1;
		}
		if (m1 > 12)//满年,月改为1(满日-》满月-》满年,所以日已经改为1了)
		{
			y1++;
			m1 = 1;
		}
		days++;
	}
	cout << days << endl;
	return 0;
}

进制转换

在这里插入图片描述
在这里插入图片描述

//机制转换
#include<iostream>     
#include<stack>
using namespace std;
int main()
{
	cout << "P是输入进制,Q是输出进制 " << endl;
	int P, Q; cin >> P >> Q;//P是输入进制,Q是输出进制
	cout << "待处理的数字 " << endl;
	int y; cin >> y;//待处理的数字
	int x = y % 10, w = 1;//x:待处理数字的个位, w:权重
	int result = 0;//暂存当前结果
	stack<int>res;

	//将P进制处理成十进制
	while (y != 0)
	{
		result += x * w;
		y = y / 10;
		x = y % 10;
		w = w * P;
	}
	cout << "十进制:" << result << endl;;//处理后的十进制数

	//将十进制处理成Q进制
	w = 1;
	x = result % Q;
	while (result != 0)
	{
		res.push(x);
		result = result / Q;
		x = result % Q;
	}
	//cout << res.size() << endl;

	while(!res.empty())
	{
		cout << res.top();
		result =  result * 10 + res.top();
		res.pop();
	}
	cout << endl << "Q进制" << result << endl;

	return 0;
}

字符串处理

在这里插入图片描述

#include<iostream>
using namespace std;
int main()
{
	string s; cin >> s;
	int len = s.size();
	int flag = 1;
	for (int i = 0; i < len / 2 && flag; i++)
	{
		if (s[i] != s[len - i - 1])
		{
			flag = 0;
			break;
		}
	}
	if (flag) cout << "YES" << endl;
	else cout << "NO" << endl;
	return 0;
}

猜你喜欢

转载自blog.csdn.net/helloworld0529/article/details/107836943