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");
}