统计字符串中连续1和连续0的个数

这是一个C++程序,用于统计字符串中连续0和1的最大个数。程序通过遍历字符串,判断字符及其前一个字符的关系来更新最大连续0和1的计数。最后输出结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


/*
#include<stdio.h>
#include<iostream>        //自己写的

using namespace std;

void getmax(char*str)
{
    int len = strlen(str);
    int max0 = 0, max1 = 0;
    int temp0 = 0, temp1 = 0;
    int i;
    for (i = 0; i < len; i++)
    {
        if (str[i] == '0')
        {
        
            temp0++;        

            if (str[i + 1] == '1')
            {
            
                if (temp0 > max0)
                    max0 = temp0;
                temp0 = 0;
            }
            else
            {
                max0 = temp0;
            }
            
        }
        if (str[i] == '1')
        {
        
            temp1++;
        
            if (str[i + 1] == '0')
            {
                if (temp1 > max1)
                    max1 = temp1;
                temp1 = 0;
            }
            else
            {
                max1 = temp1;
            }            
        }
    }
    
    cout << "the  number of '0' is : " << max0 << endl;
    cout << "the namber of '1' is: " << max1 << endl;
}

int main()
{
    char str[] = "101000000000011100000000000";
    getmax(str);
    getchar();
}
*/

#include<stdio.h>
#include<iostream>
void getmax(char *str, int *max0, int* max1) //把参数设置成指针才可以有多个输出。
                                             //
{
    int i, len, tmp_max0 = 0, tmp_max1 = 0;
    len = strlen(str);
    for (i = 0; i < len; i++)
    {
        if (str[i] == '0')
        {
            if (str[i - 1] == '1')
            {
                if (tmp_max1 > *max1)
                    *max1 = tmp_max1;
                tmp_max1 = 0;
            }
            tmp_max0++;
        }
        if (str[i] == '1')
        {
            if (str[i - 1] == '0')
            {
                if (tmp_max0 > *max0)
                    *max0 = tmp_max0;
                tmp_max0 = 0;
            }
            tmp_max1++;
        }
    }
    if (tmp_max1 > *max1)
        *max1 = tmp_max1;
    if (tmp_max0 > *max0)
        *max0 = tmp_max0;
}


int main()
{
    char str[] = "101000000000011100000000000";
    int max0 = 0, max1 = 0;
    getmax(str, &max0, &max1);
    printf("\n%s\n", str);
    printf("the number of consecutive character '0' are %d\n", max0);
    printf("the number of consecutive character '1' are %d\n", max1);
    getchar();
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值