Jump to content

Middle three digits: Difference between revisions

→‎{{header|C}}: replaced incorrect implementation ("&128" was not reasonable; inherent overflow problem)
(→‎{{header|PARI/GP}}: Marked incorrect as valid answers must always have three digits)
(→‎{{header|C}}: replaced incorrect implementation ("&128" was not reasonable; inherent overflow problem))
Line 73:
0: ****number of digits must be >= 3 and odd****</pre>
 
=={{header|C}}==#include <stdio.h>
<lang C>#include <stdiostdlib.h>
#include <string.h>
 
// we return a static buffer; caller wants it, caller copies it
#define E_SMALL 1
char * mid3(int n)
#define E_EVEN 2
static const char *errors[] = {"too small", "even length"};
 
int mid3(int num, char *buf)
{
static char buf[432] = "";
int i, mag = 1;
int numl;
int tmp = num = num < 0 ? -num : num; /* Discard sign. */
sprintf(buf, "%d", n > 0 ? n : -n);
 
l = strlen(buf);
/* A number's magnitude can be used to determine both
if (l < 3 if|| !(magl & 1281)) return E_EVEN0;
* its length and, in this case, the oddness thereof. */
l = while (tmpl /= 10)2 mag *=- 101;
buf[l + 3] = 0;
 
return buf + l;
if (mag < 100) return E_SMALL;
if (mag & 128) return E_EVEN;
 
while (num > 1000) {
num -= num / mag * mag; /* Chop left digit. */
num /= 10; /* Now the right. */
mag /= 100;
}
 
/* Populate a character buffer to handle zeroes. */
for (i = 2; i >= 0; num /= 10, --i)
buf[i] = num % 10 + '0';
 
return 0;
}
 
int main(void)
{
int x[] = {123, 12345, 1234567, 987654321, 10001, -10001,
int num;
-123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0,
char buf[4] = "";
1234567890};
 
while (scanf("%d", &num) != EOF) {
printf("%d: ", num);
 
if ((num = mid3(num, buf)) == 0)
printf("%s\n", buf);
else
puts(errors[--num]);
}
 
int i;
return 0;
char *m;
for (i = 0; i < sizeof(x)/sizeof(x[0]); i++) {
if (!(m = mid3(x[i])))
m = "error";
printf("%d: %s\n", numx[i], m);
}
return 0;
}</lang>
{{out}}
<pre>123: 123
12345: 234
1234567: 345
987654321: 654
10001: 000
-10001: 000
-123: 123
-100: 100
100: 100
-12345: 234
1: too small
2: too small
-1: too small
-10: too small
2002: even length
-2002: even length
0: too small</pre>
 
=={{header|C++}}==
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.