给定数字串,输出可能的ip地址组合!

最近看到一个面试问题,决定挺好的,能够考验一个程序员的编程功底,于是自己写了一下。
题目:给定一个数字字符串,要求输出可能的ip地址组合
      输入:12342

      输出:1.2.3.42

                  1.2.34.2

                   1.23.4.2

                    12.3.4.2

下面是我写的一个小程序,欢迎拍砖

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int *stack;
int max_top;
char *end;

void  ip_comb(int top,  char *tmp)
{
	int next_top = top;
	int next_value;
	int i;

	if(tmp > end ||
		(tmp == end && top != max_top) ){
		return;
	}

	stack[top] = stack[top] * 10 +  *tmp - '0';

	if(stack[top] > 255){
		return ;
	}
	
	//print result
	if(top == max_top && tmp == end){
		for(i =0; i < max_top; i++){
			printf("%d.", stack[i]);
		}
		printf("%d\n", stack[max_top]);
		return;
	}

	if(top < max_top){
		next_top = top + 1;
	}

	next_value = stack[next_top];

	ip_comb(next_top, tmp + 1);

	if(next_value == 0){
		stack[next_top] = 0;
		ip_comb(top, tmp + 1);
	}

	return ;
}


int main(int argc, char ** argv)
{
	char *ip_str;
	int str_len;
	int stack_len;
	//int i;

	if(argc < 3){
		printf("Usage: %s <intstr> <comb_number> \n  \t Example: ./test 123421 4 ", argv[0]);
	}

	ip_str = strdup(argv[1]);
	stack_len = atoi(argv[2]);

	max_top = stack_len -1;
	str_len = strlen(ip_str);
	end = ip_str + str_len - 1;

	stack = (int *)calloc(1, stack_len);

	//normal case
	ip_comb(0, ip_str);

	//We can comb a very long ip str
//	for(i = 0; i <= str_len - stack_len; i++)
//	{
//		stack[0] = 0;
//		ip_comb(0, ip_str + i);
//	}

	return 0;
}

 

  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值