I want to split the a given number (6 digits) after incrementing it by 1 into 2 numbers (3 digits for each one) then sum first 3 digits and last 3 digits and check if sum matches, do the process again, finally return the number that has the first and last 3 digits sum is equal.
My code splits the number , but the last 3 digits are printed reversed somehow (that's not the matter as I want the sum of them only)
but the problem comes when I try to sum every 3 digits.
int onceInATram(int x) {
// Complete this function
int n = 0;
int y = 0;
int len = 0;
int digit = 0;
int t1 = n;
int t2 = y;
int reminder1 = 0;
int reminder2 = 0;
int sum1 = 0;
int sum2 = 0;
len = (int) floor(log10(abs(x))) + 1;
do {
n = x + 1; // to add 1 to the number
while ((floor(log10(abs(n)) + 1) > len / 2)) { // split it by half
digit = n % 10;
n = n / 10;
y = (y * 10) + digit;
}
int l = 3;
while (l--) {
reminder1 = t1 % 10;
sum1 = sum1 + reminder1;
t1 = t1 / 10;
reminder2 = t2 % 10;
sum2 = sum2 + reminder2;
t2 = t2 / 10;
}
} while (sum1 != sum2);
//return(printf("%d\n%d\n", n, y)); // for debugging
return printf("%d%d\n", n, y); // '' ''
//return printf("%d\n", sum1); // '' ''
}
int main() {
int x;
scanf("%i", &x);
int result_size;
char* result = (char *) onceInATram(x);
printf("%s\n", result);
return 0;
}
and I used function but seems that nothing work!
my input: 555555
my output: 555655 > same as 555556 (incrementing by 1 but reverse last 3 digits).
expected output: 555564 (as the sum of first 3 digits == last 3 digits).
I re-wrote it to try to be simpler and more straightforward.
I came up with this:
#include <float.h>
#include <math.h>
#include <stdlib.h>
int onceInATram(int n) {
int y = 0;
int x = 0;
int t1 = n;
int t2 = y;
int reminder1 = 0;
int reminder2 = 0;
int sum1 = 0;
int sum2 = 0;
do {
n = n + 1; // to add 1 to the number
y = n % 1000; // This is the first 3 numbers
x = n / 1000; // This is the last 3 numbers
printf("%d is now split into %d and %d\n", n, x, y);
t1 = x;
t2 = y;
sum1 = 0;
sum2 = 0;
for(int l=0; l<3; ++l) {
reminder1 = t1 % 10;
sum1 = sum1 + reminder1;
t1 = t1 / 10;
reminder2 = t2 % 10;
sum2 = sum2 + reminder2;
t2 = t2 / 10;
}
} while (sum1 != sum2);
return 1000*x+y;
}
int main() {
int x;
scanf("%d", &x);
int result = onceInATram(x);
printf("The Final Answer is %d\n", result);
return 0;
}
Example Input / Output:
123456
The Final Answer is 123501
because 1 + 2 + 3 == 6 == 5 + 0 + 1