蓝蓝计算机考研算法-day02字符串中字符不同个数和两数的最小公倍数

94 阅读1分钟

编写一个函数,计算字符串中含有的不同字符的个数。字符在ASCI码范围内(0~127,包括0和127),换行表示结束符,不算在字符里。不在范围内的不作统计。多个相同的字符只计算一次例如,对于字符串abaca而言,有a、b、c三种不同的字符,因此输出3。数据范围:1<=n<=500

输入描述 输入一行没有空格的字符串。 输出描述: 输入字符串中范围在(0~127,包括0和127)字符的种数。输入:

#include <string> 
using namespace std; 
int countChars(string str) 
{ 
	bool char_set[128] = { false }; 
	int count = 0; 
	// 遍历每一个字符 
	for (int i = 0; i < str.size(); i++) 
	{ 
		// 该字符是否已经统计过 
		if (char_set[str[i]] == false) 
		{ 
			// 若未统计过,则将其置为true 
			char_set[str[i]] = true; 
			// 统计不同字符的个数 
			count++; 
		} 
	} 
	return count; 
} 
int main() 
{ 
	char str[500]; 
	gets(str);
	cout << countChars(str); 
	return 0; 
}

3622b3657aeadf8c81d64d6530058e4.png

从键盘输入两个数字n,m,求解n和m的最小公倍数。

#include<stdio.h>
int main(){
	int i,j,x,y;
	printf("输入第一个数:");
	scanf("%d",&x);
	printf("输入第二个数:");
	scanf("%d",&y);
	for(i=1,j=1;(x*j)<=(x*y);){
		if(i*x<j*y)i++;
		else if(i*x>j*y)j++;
		else{
			printf("最小公倍数为:%d",i*x);
			break;
		}
	}
}

53d830a2b135dacc6d094d99e27ee85.png