/*
要求如下:
例如 : 000111100101011001010101010101110
*/
#include <stdio.h>
#include <stdlib.h>
void calculate (const char* str ,int* max0,int *max1){//通过传入 两个指针变量 可以带回两个值,相当于 返回两个值
int temp0 = 0;//用来记录连续0 的次数
int temp1 = 0;//用来记录连续1 的次数
while (*str ){
if (*str =='0')
{
(*max0) ++;
if(*(++str) =='1'){
if (temp0<*max0){// 更新temp0的值
temp0 = *max0;
}
*max0 =0;//重新置0,以便寻找下一个可能比较大的连续出现的次数
}
}
else if (*str =='1')
{
(*max1) ++;
if (*(++str)=='0'){
if (temp1<*max1){//更新temp1的值
temp1 = *max1;
}
*max1 = 0;
}
}
}
*max0 = temp0;//将值 通过指针带回
*max1 = temp1;//将值 通过指针带回
}
来测试一下 void main (){
char string[] = "0001111110010";
int max0 =0;
int max1 = 0;
calculate (string,&max0,&max1);
printf ("max0 is %d \n ",max0);
printf ("max1 is %d \n ",max1);
system("pause");
}
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------
/*
2 编程实现 两个 任意长度的正整数 相加 ,
注:其实就是字符串的相加问题,进行进位处理。
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
char * addBigInt(char* num1, char* num2){
int c = 0; // 保留 要进位的数字
int i = strlen(num1) - 1;//最低位的下标
int j = strlen(num2) - 1;//最低位的下标
int maxLength = strlen(num1) > strlen(num2) ? strlen(num1) + 1 : strlen(num2) + 1; //得到相加后可能的最大位数,相加后可能会产生进位
char * res = (char*)malloc(maxLength + 1);// 多出一位用来存放 结束符'\0'
if (res == NULL){
printf("malloc error !\n");
exit(-1);
}
res[maxLength] = '\0';
int k = strlen(res) - 1;//表示结果的最低位
while ((i >= 0) && (j >= 0)){
res[k] = ((num1[i] - '0') + (num2[j] - '0') + c) % 10 + '0';
/*实际上就是把数字字符转换为数字,之后两个数字相加对10取余
可以得到本位的值, +'0' :就是把数字转换为字符 */
c = ((num1[i] - '0') + (num2[j] - '0') + c) / 10;// 进位值
--j;
--i;
--k;
}
while (i >= 0){//把剩余的位数 进行相应的转化。
res[k] = (num1[i] - '0' + c) % 10 + '0';
c = ((num1[i] - '0' + c)) / 10;
--i;
--k;
}
while (j >= 0){//把剩余的位数 进行相应的转化
res[k] = (num2[j] - '0' + c) % 10 + '0';
c = ((num1[j] - '0' + c)) / 10;
--j;
--k;
}
res[0] = c + '0';//最高位数字字符
if (res[0] != '0')//最高位进位了,res 就不等于0
{
return res;
}
else{//最高位没有进位
res = res + 1;
return res;
}
}
下面写一个测试程序。
void main(){
char str1[] = "111111111111111";
char str2[] = "222222222222222";
char str3[] = "1234";
char* result = NULL;
result = addBigInt(str1, str2);
printf(" %s + %s = %s\n", str1, str2, result);
result = addBigInt(str2, str3);
printf("\n %s + %s = %s\n", str2, str3, result);
system("pause");
}
如果各位朋友发现程序有什么问题,欢迎大家一起交流。