reverse or rotate

The input is a string str of digits. Cut the string into chunks of size sz (ignore the last chunk if its size is less than sz).
If a chunk represents an integer such as the sum of the cubes of its digits is divisible by 2, reverse it; otherwise rotate it to the left by one position. Put together these modified chunks and return the result as a string.

If
sz is <= 0 or if str is empty return “”
sz is greater (>) than the length of str it is impossible to take a chunk of size sz hence return “”.
Examples:
revrot(“123456987654”, 6) –> “234561876549”
revrot(“123456987653”, 6) –> “234561356789”
revrot(“66443875”, 4) –> “44668753”
revrot(“66443875”, 8) –> “64438756”
revrot(“664438769”, 8) –> “67834466”
revrot(“123456779”, 8) –> “23456771”
revrot(“”, 8) –> “”
revrot(“123456779”, 0) –> “”

char* revrot(char* s, int sz) {
 if(!sz || !s)
        return "";
    int len=strlen(s);
    int curgroup=0;
    int index = sz;
    int validGroup=len/sz;

    while(curgroup<validGroup)
    {
        int sum=0;
        for(int i=0;i<sz;i++)
        {
            sum+=(s[i+curgroup*sz]-48)*(s[i+curgroup*sz]-48)*(s[i+curgroup*sz]-48);
        }
        if(sum%2 == 0)//reverse
        {
            for(int i=0;i<sz/2;i++)
            {
                char temp=s[i+curgroup*sz];
                s[i+curgroup*sz]=s[curgroup*sz+sz-1-i];
                s[curgroup*sz+sz-1-i]=temp;
            }
        }
        else//rotate
        {
            char* tem = (char*)malloc(sz);
            for(int i=0;i<sz-1;i++)
            {
                tem[i]=s[curgroup*sz+i+1];
            }
            tem[sz-1]=s[curgroup*sz];
            memcpy((void*)(s+curgroup*sz),tem,sz);
            free(tem);
        }


        curgroup++; 
    }
    s[sz*validGroup]=0;
    return s;
}

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

char* revrot(char* s, int sz);

void dotest(char* s, size_t sz, char *expr)
{
    char *act = revrot(s, sz);
    if(strcmp(act, expr) != 0)
        printf("Error. Expected %s but got %s\n", expr, act);
    cr_assert_str_eq(act, expr, "");
}
Test(revrot, ShouldPassAllTheTestsProvided)
{      
    char s[]= "1234";
    dotest(s, 0, "");
    char s1[] = "";
    dotest(s1, 0, "");
    char s2[] = "1234";
    dotest(s2, 5, "");
    char s3[] = "733049910872815764";
    dotest(s3, 5, "330479108928157");
    char s4[] = "73304991087281576455176044327690580265896";
    dotest(s4, 8, "1994033775182780067155464327690480265895");
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值