数字转换成字符串

时间:2022-03-13 06:18:05

描述:

将一个int类型的数字转化为字符串,并判断有无重复字符串(长度应大于2)有返回1,无返回2。

代码:

#include <iostream>
#define MAX 200
using namespace std;
int ltoAandRepeat(unsigned int num)
{
	char p1[MAX], p[MAX];
	int count = 0;
	int temp = num;
	//计算整数num几位数
	while (temp > 0)
	{
		temp /= 10;
		count++;
	}
	//整数转换成字符串
	temp = num;
	int i;
	for (i = 0; i < count; i++)
	{
		p1[i] = temp % 10+'0';
		temp /= 10;
	}
	for (i = 0; i < count; i++)
	{
		p[count - 1 - i] = p1[i];
	}
	p[count] = '\0';
	cout << p<<endl;

	//判断有无重复字符串
	int n = 0;
	int j;
	for (i = 0; i < count - 1; i++)
	{
		for (j = i + 1; j < count; j++)
		{
			if (p[i] == p[j]&&j>=i+2)	//不允许有重复的,如111不被认为是重复字符串
										// 如果允许,则if(p[i]==p[j])即可
			{
				if (p[++i] == p[++j])
					return 1;
			}
		}
	}
	return 2;
}

int main()
{
	int num;
	cin >> num;
	cout << ltoAandRepeat(num) << endl;
	cin.get();
	cin.get();
}

参考代码:

#include <iostream>
using namespace std;
#define MAX 200
int ltoAandRepeat(unsigned int theNum, char*s)
{
	char str[MAX];
	char Repeat[MAX];
	int interg, remainder, i = 0, j , z = 0, k = 0, temp;
	//数字转换成字符串
	remainder = theNum % 10;
	interg = theNum / 10;
	while (interg)
	{
		str[i] = remainder + 48;
		i++;
		remainder = interg % 10;
		interg = interg / 10;
	}
	str[i] = remainder + 48;
	i++;
	str[i] = '\0';
	for (z = 0, j = i - 1; j >= 0; j--, z++)
	{
		s[z] = str[j];
	}
	s[z] = '\0';
	cout << theNum<<" has been transferred into a string: "<<s<<endl;

	for (i = 0; s[i] != '\0'; i++)// 判断有无重复字符串
	{
		for (j = 0; j < i; j++)// 判断之前是否出现过该字符
		{
			if (s[j] == s[i])// 若出现过,则从此位置开始向后判断有多少位重复
			{
				z = i;
				z++;
				j++;
				temp = 1;
				while (s[j] == s[z] && s[z] != '\0')// 实现可重叠的重复字符串
													// 实现无重叠的重复字符串,用while(s[j]==s[z]&&s[z]!='\0'&&j<i)
				{
					z++;
					j++;
					temp++;
				}
				if (temp > 1)
				{
					for (k = 0; k < temp; k++,i++)
					{
						Repeat[k] = s[i];
					}
					Repeat[k] = '\0';
					cout << s << " has duplicated sub-string(s), which is " << Repeat << endl;
					return 1;
				}
			}
		}
	}
	return 2;
}

int main()// 主函数
{
	int number, temp1, re;
	char s[MAX];
//	temp1=(cin >> number);
	temp1 = scanf("%d", &number);
	while (temp1 == 1)// 结束标志是EOF,即按Ctrl+C
	{
		re = ltoAandRepeat(number, s);
		cout << re << endl;
		printf("Please enter the next number: ");
		temp1 = scanf("%d", &number);
	}
	return 0;
}