Skip to content

Instantly share code, notes, and snippets.

@iscgar
Last active August 15, 2020 19:30
Show Gist options
  • Save iscgar/c22ee0fcfe438b429b141877a8cd67ee to your computer and use it in GitHub Desktop.
Save iscgar/c22ee0fcfe438b429b141877a8cd67ee to your computer and use it in GitHub Desktop.
Embedded Software Engineer Solves FizzBuzz
#include <stdio.h>
enum
{
FIZZ = 1,
BUZZ = 2
};
static int get_natural(const char *val, unsigned int *out)
{
unsigned int prev = *out = 0;
if (*val == '\0')
{
return 0;
}
while (isdigit(*val))
{
unsigned int dig = *val - '0';
*out *= 10;
*out += dig;
if ((*out - dig) / 10 != prev)
{
return 0;
}
prev = *out;
++val;
}
return *val == '\0';
}
int main(int argc, const char *argv[])
{
unsigned int max;
if ((argc != 2) || (!get_natural(argv[1], &max)))
{
puts("Usage:\r\n fizzbuzz <max-natural-number>");
}
else if (max > 0)
{
register unsigned int cur = max;
static const char *str[] = { "", "Fizz", "Buzz" };
for (;;)
{
unsigned int rnd = 0x2486, msk = 0x3659;
while (rnd)
{
register unsigned int x = rnd & 3;
if (x > cur)
{
x = cur;
}
while (x--)
{
printf("%d ", max - cur + 1);
--cur;
}
if (!cur)
goto end;
printf("%s%s ", str[msk & FIZZ], str[msk & BUZZ]);
--cur;
rnd >>= 2;
msk >>= 2;
}
}
end:
printf("\r\n");
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment