For one of my university assignments, we were asked to take an unsigned int
, reverse its digits, find the absolute difference between the original and reversed, then reverse that, and you receive the "Magic Number".
$$ R(\ \lvert R(A) - A\rvert\ )$$
where \$A\$ is a positive integer and \$R(n)\$ means reverse.
We were also asked to take multiple inputs at once and keep track of the largest absolute difference between all inputs.
#include <stdio.h>
// Reverse an unsigned integer
unsigned int reverseInteger(unsigned int input) {
unsigned int output = 0;
while (input != 0) { // Terminate when input is 0
output = output * 10 + input % 10; // Can't use =* here, order of operations!
input /= 10;
}
return output;
}
// Find the absolute differnece between a reversed number, then reverse the absolute difference
unsigned int generateMagicNumber(unsigned int input) {
/* Find Absolute Difference */
if (input < reverseInteger(input)) {
input = reverseInteger(input); // If the result will be negative, reverse the number before finding the difference
input -= reverseInteger(input);
}
else {
input -= reverseInteger(input);
}
largestAbsoluteDifference(input);
return reverseInteger(input); // Reverse absolute difference to find the magic number
}
// Find the largest of all values passed to this function
unsigned int largestAbsoluteDifference(unsigned int input) {
static unsigned int keep = 0; // Must be static!
return (input > keep) ? (keep = input) : keep; // If the input is greater than the current, store the input. Else, keep the current.
}
int main() {
int inputs;
printf("Enter number of inputs: ");
scanf("%d", &inputs);
printf("Enter space separated: ");
for (int i = 0; i < inputs; i++) {
unsigned int num;
scanf("%u", &num);
if (i == 0) { printf("\nOutput: "); } // Append label only on first iteration
printf("%u ", generateMagicNumber(num)); // Generate and print the magic number
}
printf("\nLargest Absolute Difference: %u\n", largestAbsoluteDifference(0)); // Must pass 0 into largestAbsoluteDifference
}
Example Input / Output
Enter number of inputs: 5 Enter space separated: 23 512 454 94 100 Output: 9 792 0 54 99 Largest Absolute Difference: 297
Notes / Concerns
- The way I wrote the
largestAbsoluteDifference
seems slimy me to (having to pass 0 to get the result). - I've got in the habit of calling functions inside a
printf
instead of storing the value in a variable and then printing the variable (see lines 56, 59). Is this okay? - In
generateMagicNumber
I had to make sure finding the difference wouldn't result in a negative number (which you can't store in anunsigned int
). Is my method the best way to find the absolute value like that?
R
intended to be bijective? As implementedreverseInteger(90)
yields9
, which when reversed again yields9
. If bijectivity is required, then you might have to operate on strings... \$\endgroup\$