字符串右移N位题目

  当初想了半天没想出来。。(脑子太笨了。。。。T.T)

回家仔细考虑了下。 实现如下:

追加解题思路。


右移n位表示有n位数字要移动到的位置要超过字符串长度。程序中count用来表示已经有多少位 移动超过长度了。 

然后,head的值每次和被移动后的位置的值进行交换,反复执行,知道交换的位置又回到head

如果count没有达到n,那么head值+1, 继续执行。(主要是偶数位的字符串移动偶数位的时候。)

void
move_string(char *msg, int steps)
{
  int len;
  int pos;
  int head;
  char tmp;
  int count;
  
  if(msg == NULL)return;
  len = strlen(msg);
  steps = steps % len;
  head = 0;
  count = 0;

  while(1){
    tmp = msg[head];

    if(pos + steps >= len){
      count++;
    }
    
    pos = (pos + steps) % len;
    // back to head do next loop.
    if(pos == head){
      if(count == steps){
	break;
      }
      head++;
      pos = head;
      continue;
    }
    msg[head] = msg[pos];
    msg[pos] = tmp;
  }

  printf("the result : %s\n", msg);
}


转载于:https://my.oschina.net/hjxc/blog/365755

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值