Last active
May 17, 2017 14:14
-
-
Save Michael-F-Bryan/cb07added5bbc40095104d37d7e54a91 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <string.h> | |
// Naive algorithm to "shift" a decimal number left `length` digits. | |
int stretch(int n, int length) { | |
for (int i = 0; i < length; ++i) { | |
n *= 10; | |
} | |
return n; | |
} | |
#define XOR_SWAP(a,b) do\ | |
{\ | |
a ^= b;\ | |
b ^= a;\ | |
a ^= b;\ | |
} while (0) | |
// String reversing function copied straight from stack overflow. | |
void reverse_string(char * str) | |
{ | |
if (str) | |
{ | |
char * end = str + strlen(str) - 1; | |
// walk inwards from both ends of the string, | |
// swapping until we get to the middle | |
while (str < end) | |
{ | |
XOR_SWAP(*str, *end); | |
str++; | |
end--; | |
} | |
} | |
} | |
// mult takes a number and pads it out with the specified number of zeroes. It | |
// then writes that number to the provided buffer, making sure to group into | |
// threes for readability. | |
void mult(int number, int size, char* buffer, int buffer_length) { | |
int i = 0, digits_in_group = 0; | |
// Add the specified number of "0" digits to some temporary number | |
int temp = stretch(number, size); | |
while (temp > 0 && i < buffer_length) { | |
// Get the rightmost digit and add it to our buffer | |
int current_digit = temp % 10; | |
buffer[i] = current_digit + '0'; | |
digits_in_group++; | |
// Add the extra space if necessary (making sure to skip when the final | |
// string length is a multiple of 3) | |
if (digits_in_group > 2 && temp >= 10) { | |
i++; | |
buffer[i] = ' '; | |
digits_in_group = 0; | |
} | |
temp /= 10; | |
i++; | |
} | |
// Finally, we need to reverse the string because we populated it backwards | |
reverse_string(buffer); | |
} | |
typedef struct Input { | |
int number; | |
int length; | |
char* should_be; | |
} Input; | |
int main() { | |
Input inputs[7] = { | |
{51, 0, "51"}, | |
{51, 1, "510"}, | |
{51, 2, "5 100"}, | |
{51, 3, "51 000"}, | |
{51, 4, "510 000"}, | |
{51, 5, "5 100 000"}, | |
{51, 6, "51 000 000"}, | |
}; | |
for (int i = 0; i < 7; ++i) { | |
Input input = inputs[i]; | |
printf("mult(%d, %d) => %10s ", input.number, input.length, input.should_be); | |
// Create a temporary buffer and clear it | |
char buffer[15]; | |
memset(buffer, 0, sizeof(buffer)); | |
mult(input.number, input.length, buffer, 15); | |
if (strcmp(buffer, input.should_be)) { | |
printf("✘ (got \"%s\")\n", buffer); | |
} else { | |
printf("✓\n"); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment