最大递增数

给定一串数字,寻找其中最大的递增数(连续)
12345129234
则最大递增数为12345

最开始写了这样代码

#include <iostream>
using namespace std;

void selectString(char []);
int main(){
	const int Size = 1000;
	char s[Size];
	cout << "Enter a string:\n";
	cin >> s;
	selectString(s);
	cout << endl;
	system ("pause");
	return 0;
}
void selectString(char str[]){
	int position = 0;
	int length = 0;
	int maxlen = 0;
	for (int i = 0; str[i] != '\0'; i++){
		if (str[i] - '0' < str[i+1] - '0')
			length++;//递增则length加1
		else
			length = 0;//下降则length变为0
		if (length > maxlen){
			maxlen = length;
			position = i + 1 - maxlen;//这里为最小元素的位置
		}
	}
	
	for (int j = 0; j <= maxlen; j++){
		cout << str[position++];
	}
}

但是这样的代码对于135256而言只得到了135,没有的得到最大的递增数修改selectString()

	s1.assign(str);//将字符数组str赋给s1
        s2 = s1.substr(position, maxlen);//s2是s1的一个字串,从position开始长度为maxlen
}
else if(length == maxlen){
	s3 = s1.substr(i+1-length, length);
	prelong = atoi(s2.c_str());
	postlong = atoi(s3.c_str());
	if( prelong < postlong)
		position = i + 1 - length;
atoi函数是C语言中,对于C++中的string是不适用的,
所以需要将C++中的字符串变为C中字符串,s2.c_str()  s3.c_str()
atoi将字符串转换成整型数。
当位数相同时比较两个数的大小就可以得到256
额 直接用s2和s3比较也是可以的。

但是这个程序测试仍然有点问题,例如780123179
最大的递增数是179而不是0123

一直想通过位数解决,零开始的话会比多一位,当length比maxlen多一位时候,开头是零则,可以换下
陷入误区,
其实找 递增数的话,只要把零忽略就好了,遇到0时候length不变化就可以了

#include <iostream>
#include <stdlib.h>
#include <string>
using namespace std;

void selectString(char []);

int main(){
	const int Size = 1000;
	char s[Size];
	cout << "Enter a string:\n";
	cin >> s;
	cout << "The longestAndBigest number:\n";
	selectString(s);
	cout << endl;
	system ("pause");
	return 0;
}

void selectString(char str[]){
	string s1;
	string s2;
	string s3;
	s1.assign(str);
	int position = 0;
	int length = 0;
	int maxlen = 0;
	for (int i = 0; str[i] != '\0'; i++){
		if (str[i] - '0' < str[i+1] - '0'){
			if (str[i] == '0')
				;
			else
				length = length + 1;
		}else
			length = 0;
		
		if (length > maxlen){
			maxlen = length;
			position = i + 1 - maxlen;
			s2 = s1.substr(position, maxlen);
		}else if(length == maxlen){
			s3 = s1.substr(i + 1 - length, length);
			if (s3 > s2){
				position = i + 1 - length;
				s2 = s1.substr(position, maxlen);
			}
		}
	}

	for (int j = 0; j <= maxlen; j++){
		cout << str[position++];
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值