Middle three digits

From Rosetta Code
Revision as of 00:13, 17 June 2013 by rosettacode>Axtens (FBSL)
Task
Middle three digits
You are encouraged to solve this task according to the task description, using any language you may know.

The task is to:

Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible.
Note: The order of the middle digits should be preserved.

Your function should be tested with the following values; the first line should return valid answers, those of the second line should return clear indications of an error:

123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345
1, 2, -1, -10, 2002, -2002, 0

Show your output on this page.

Ada

<lang Ada>with Ada.Text_IO;

procedure Middle_Three_Digits is

  Impossible: exception;
  function Middle_String(I: Integer; Middle_Size: Positive) return String is
     S: constant String := Integer'Image(I);
     First: Natural := S'First;
     Full_Size, Border: Natural;
  begin
     while S(First) not in '0' .. '9' loop -- skip leading blanks and minus
        First := First + 1;
     end loop;
     Full_Size := S'Last-First+1;
     if (Full_Size < Middle_Size) or (Full_Size mod 2 = 0) then
        raise Impossible;
     else
        Border := (Full_Size - Middle_Size)/2;
        return S(First+Border .. First+Border+Middle_Size-1);
     end if;
  end Middle_String;
  Inputs: array(Positive range <>) of Integer :=
    (123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345,
     1, 2, -1, -10, 2002, -2002, 0);
  Error_Message: constant String := "number of digits must be >= 3 and odd";
  package IIO is new Ada.Text_IO.Integer_IO(Integer);

begin

  for I in Inputs'Range loop
     IIO.Put(Inputs(I), Width => 9);
     Ada.Text_IO.Put(": ");
     begin
        Ada.Text_IO.Put(Middle_String(Inputs(I), 3));
     exception
        when Impossible => Ada.Text_IO.Put("****" & Error_Message & "****");
     end;
     Ada.Text_IO.New_Line;
  end loop;

end Middle_Three_Digits;</lang>

Output:
      123: 123
    12345: 234
  1234567: 345
987654321: 654
    10001: 000
   -10001: 000
     -123: 123
     -100: 100
      100: 100
   -12345: 234
        1: ****number of digits must be >= 3 and odd****
        2: ****number of digits must be >= 3 and odd****
       -1: ****number of digits must be >= 3 and odd****
      -10: ****number of digits must be >= 3 and odd****
     2002: ****number of digits must be >= 3 and odd****
    -2002: ****number of digits must be >= 3 and odd****
        0: ****number of digits must be >= 3 and odd****

Aime

<lang aime>void m3(integer i) {

   text s;
   s = itoa(i);
   if (character(s, 0) == '-') {
       s = delete(s, 0);
   }
   if (length(s) < 3) {
       v_integer(i);
       v_text(" has not enough digits\n");
   } elif (length(s) & 1) {
       o_winteger(9, i);
       o_text(": ");
       o_text(cut(s, length(s) - 3 >> 1, 3));
       o_byte('\n');
   } else {
       v_integer(i);
       v_text(" has an even number of digits\n");
   }

}

void middle_3(...) {

   integer i;
   i = 0;
   while (i < count()) {
       m3($i);
       i += 1;
   }

}

integer main(void) {

   middle_3(123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100,
            -12345, 1, 2, -1, -10, 2002, -2002, 0);
   return 0;

}</lang>

Output:
      123: 123
    12345: 234
  1234567: 345
987654321: 654
    10001: 000
   -10001: 000
     -123: 123
     -100: 100
      100: 100
   -12345: 234
1 has not enough digits
2 has not enough digits
-1 has not enough digits
-10 has not enough digits
2002 has an even number of digits
-2002 has an even number of digits
0 has not enough digits

AWK

<lang AWK>#!/bin/awk -f

  1. use as: awk -f middle_three_digits.awk

BEGIN { n = split("123 12345 1234567 987654321 10001 -10001 -123 -100 100 -12345 1 2 -1 -10 2002 -2002 0", arr)

for (i=1; i<=n; i++) { if (arr[i] !~ /^-?[0-9]+$/) { printf("%10s : invalid input: not a number\n", arr[i]) continue }

num = arr[i]<0 ? -arr[i]:arr[i] len = length(num)

if (len < 3) { printf("%10s : invalid input: too few digits\n", arr[i]) continue }

if (len % 2 == 0) { printf("%10s : invalid input: even number of digits\n", arr[i]) continue }

printf("%10s : %s\n", arr[i], substr(num, len/2, 3)) } } </lang>

Output:
       123 : 123
     12345 : 234
   1234567 : 345
 987654321 : 654
     10001 : 000
    -10001 : 000
      -123 : 123
      -100 : 100
       100 : 100
    -12345 : 234
         1 : invalid input: too few digits
         2 : invalid input: too few digits
        -1 : invalid input: too few digits
       -10 : invalid input: too few digits
      2002 : invalid input: even number of digits
     -2002 : invalid input: even number of digits
         0 : invalid input: too few digits

Bracmat

<lang bracmat>( ( middle3

 =   x p
   .     @(!arg:? [?p:? [(1/2*!p+-3/2) %?x [(1/2*!p+3/2) ?)
       & !x
     |   !arg
         ( !p:<3&"is too small"
         | "has even number of digits"
         )
 )

& 123 12345 1234567 987654321 10001 -10001 -123 -100 100

     -12345 1 2 -1 -10 2002 -2002 0
 : ?L

& whl'(!L:%?e ?L&out$(middle3$!e)) & ); </lang> Output:

123
234
345
654
000
000
123
100
100
234
1 is too small
2 is too small
-1 is too small
-10 is too small
2002 has even number of digits
-2002 has even number of digits
0 is too small

C

<lang c>#include <stdio.h>

  1. include <stdlib.h>
  2. include <string.h>

// we return a static buffer; caller wants it, caller copies it char * mid3(int n) { static char buf[32]; int l; sprintf(buf, "%d", n > 0 ? n : -n); l = strlen(buf); if (l < 3 || !(l & 1)) return 0; l = l / 2 - 1; buf[l + 3] = 0; return buf + l; }

int main(void) { int x[] = {123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0, 1234567890};

int i; char *m; for (i = 0; i < sizeof(x)/sizeof(x[0]); i++) { if (!(m = mid3(x[i]))) m = "error"; printf("%d: %s\n", x[i], m); } return 0; }</lang>

C++

<lang cpp>#include <iostream>

  1. include <sstream>
  2. include <string>

// @author Martin Ettl // @date 2013-02-04

/**

* Convert variables of type T to std::string
*
*
* @param d --> digit of type T
*
* @return <-- the corresponding string value
*/

template <typename T> const std::string toString(const T &d) {

   std::ostringstream result;
   result << d;
   return result.str();

}

/**

* Determine the middle n digits of the integer. If it is not possible to determine the
* the middle n digits, an empty string is provided.
*
* @param iDigit --> The digit to test
* @param n      --> The number of digits inbetween
*
* @return <-- the middle three digits
*/

std::string strMiddleNDigits(int iDigit, const int &n) {

   // is negative: --> convert to a positive number
   if(iDigit<0)
   {
       iDigit*=-1;
   }
   // convert to string
   std::string strNumber (toString(iDigit));
   size_t len(strNumber.length());
   if( (len < n) || (len % 2 == 0) )
   {
       return "";
   }
   size_t mid(len/2);
   return strNumber.substr(mid-n/2, n);

}

/**

* Determine the middle three digits of the integer. If it is not possible to determine the
* the middle three digits, an empty string is provided.
*
* @param iDigit --> The digit to test
*
* @return <-- the middle three digits
*/

std::string strMiddleThreeDigits(int iDigit) {

   return strMiddleNDigits(iDigit,3);

}

int main() {

   const int iPassing[] = {123, 12345, 1234567, 987654321, 10001, -10001,
                           -123, -100, 100, -12345
                          };
   for(unsigned int ui = 0; ui < 10; ++ui)
   {
       std::cout << "strMiddleThreeDigits("<< iPassing[ui] <<"): "
                 << strMiddleThreeDigits(iPassing[ui])<< "\n";
   }
   const int iFailing[] = {1, 2, -1, -10, 2002, -2002, 0};
   for(unsigned int ui = 0; ui < 7; ++ui)
   {
       std::string strResult = strMiddleThreeDigits(iFailing[ui]);
       std::cout << "strMiddleThreeDigits("<< iFailing[ui] <<"): "
                 << (strResult.empty()?"Need odd and >= 3 digits":strResult)
                 << "\n";
   }
   return 0;

} </lang>

Output:
strMiddleThreeDigits(123): 123
strMiddleThreeDigits(12345): 234
strMiddleThreeDigits(1234567): 345
strMiddleThreeDigits(987654321): 654
strMiddleThreeDigits(10001): 000
strMiddleThreeDigits(-10001): 000
strMiddleThreeDigits(-123): 123
strMiddleThreeDigits(-100): 100
strMiddleThreeDigits(100): 100
strMiddleThreeDigits(-12345): 234
strMiddleThreeDigits(1): Need odd and >= 3 digits
strMiddleThreeDigits(2): Need odd and >= 3 digits
strMiddleThreeDigits(-1): Need odd and >= 3 digits
strMiddleThreeDigits(-10): Need odd and >= 3 digits
strMiddleThreeDigits(2002): Need odd and >= 3 digits
strMiddleThreeDigits(-2002): Need odd and >= 3 digits
strMiddleThreeDigits(0): Need odd and >= 3 digits

COBOL

<lang COBOL>identification division. program-id. middle3. environment division. data division. working-storage section. 01 num pic 9(9).

   88 num-too-small    values are -99 thru 99.

01 num-disp pic ---------9.

01 div pic 9(9). 01 mod pic 9(9). 01 mod-disp pic 9(3).

01 digit-counter pic 999. 01 digit-div pic 9(9).

   88  no-more-digits  value 0.

01 digit-mod pic 9(9).

   88  is-even         value 0.

01 multiplier pic 9(9).

01 value-items.

   05  filler  pic s9(9) value 123.
   05  filler  pic s9(9) value 12345.
   05  filler  pic s9(9) value 1234567.
   05  filler  pic s9(9) value 987654321.
   05  filler  pic s9(9) value 10001.
   05  filler  pic s9(9) value -10001.
   05  filler  pic s9(9) value -123.
   05  filler  pic s9(9) value -100.
   05  filler  pic s9(9) value 100.
   05  filler  pic s9(9) value -12345.
   05  filler  pic s9(9) value 1.
   05  filler  pic s9(9) value 2.
   05  filler  pic s9(9) value -1.
   05  filler  pic s9(9) value -10.
   05  filler  pic s9(9) value 2002.
   05  filler  pic s9(9) value -2002.
   05  filler  pic s9(9) value 0.
   

01 value-array redefines value-items.

   05  items   pic s9(9)  occurs 17 times indexed by item.

01 result pic x(20).

procedure division. 10-main.

   perform with test after varying item from 1 by 1 until items(item) = 0
       move items(item) to num
       move items(item) to num-disp
       perform 20-check
       display num-disp " --> " result
   end-perform.
   stop run.
   

20-check.

   if num-too-small
       move "Number too small" to result
       exit paragraph
   end-if.
   perform 30-count-digits.
   divide digit-counter by 2 giving digit-div remainder digit-mod.
   if is-even
       move "Even number of digits" to result
       exit paragraph
   end-if.
   
   *> if digit-counter is 5, mul by 10
   *> if digit-counter is 7, mul by 100
   *> if digit-counter is 9, mul by 1000
       
   if digit-counter > 3
       compute multiplier rounded = 10 ** (((digit-counter - 5) / 2) + 1) 
       divide num by multiplier giving num
       divide num by 1000 giving div remainder mod
       move mod to mod-disp
   else
       move num to mod-disp
   end-if.
   move mod-disp to result.
   exit paragraph.
   

30-count-digits.

   move zeroes to digit-counter.
   move num to digit-div.
   perform with test before until no-more-digits
       divide digit-div by 10 giving digit-div remainder digit-mod
       add 1 to digit-counter
   end-perform.
   exit paragraph.</lang>

Output

       123 --> 123
     12345 --> 234
   1234567 --> 345
 987654321 --> 654
     10001 --> 000
    -10001 --> 000
      -123 --> 123
      -100 --> 100
       100 --> 100
    -12345 --> 234
         1 --> Number too small
         2 --> Number too small
        -1 --> Number too small
       -10 --> Number too small
      2002 --> Even number of digit
     -2002 --> Even number of digit
         0 --> Number too small

Common Lisp

<lang lisp> (defun mid3 (n)

 (let ((a (abs n))
       (hmd)) ; how many digits
   (labels ((give (fmt &optional x y) (return-from mid3 (format nil fmt x y)))
            (need (x) (give "Need ~a digits, not ~d." x hmd))
            (nbr (n) (give "~3,'0d" n)))
     (when (zerop n) (give "Zero is 1 digit"))
     (setq hmd (truncate (1+ (log a 10))))
     (cond ((< hmd 3) (need "3+"))
           ((= hmd 3) (nbr a))
           ((evenp hmd) (need "odd number of"))
           (t (nbr (mod (truncate a (expt 10 (/ (- hmd 3) 2))) 1000)))))))

</lang>

Test code:

<lang lisp> (loop as n in '(123 12345 1234567 987654321

                   10001 -10001 -123 -100 100 -12345
                   1 2 -1 -10 2002 -2002 0)
     do (format t "~d:~12t~a~%" n (mid3 n)))

</lang>

Output:
123:        123
12345:      234
1234567:    345
987654321:  654
10001:      000
-10001:     000
-123:       123
-100:       100
100:        100
-12345:     234
1:          Need 3+ digits, not 1.
2:          Need 3+ digits, not 1.
-1:         Need 3+ digits, not 1.
-10:        Need 3+ digits, not 2.
2002:       Need odd number of digits, not 4.
-2002:      Need odd number of digits, not 4.
0:          Zero is 1 digit

D

<lang d>import std.stdio, std.traits, std.conv;

string middleThreeDigits(T)(in T n) if (isIntegral!T) {

   auto s = n < 0 ? n.text()[1 .. $] : n.text();
   auto len = s.length;
   if (len < 3 || len % 2 == 0)
       return "Need odd and >= 3 digits";
   auto mid = len / 2;
   return s[mid - 1 .. mid + 2];

}

void main() {

   immutable passing = [123, 12345, 1234567, 987654321, 10001, -10001,
           -123, -100, 100, -12345, long.min, long.max];
   foreach (n; passing)
       writefln("middleThreeDigits(%s): %s", n, middleThreeDigits(n));
   immutable failing = [1, 2, -1, -10, 2002, -2002, 0,int.min,int.max];
   foreach (n; failing)
       writefln("middleThreeDigits(%s): %s", n, middleThreeDigits(n));

}</lang>

Output:
middleThreeDigits(123): 123
middleThreeDigits(12345): 234
middleThreeDigits(1234567): 345
middleThreeDigits(987654321): 654
middleThreeDigits(10001): 000
middleThreeDigits(-10001): 000
middleThreeDigits(-123): 123
middleThreeDigits(-100): 100
middleThreeDigits(100): 100
middleThreeDigits(-12345): 234
middleThreeDigits(-9223372036854775808): 368
middleThreeDigits(9223372036854775807): 368
middleThreeDigits(1): Need odd and >= 3 digits
middleThreeDigits(2): Need odd and >= 3 digits
middleThreeDigits(-1): Need odd and >= 3 digits
middleThreeDigits(-10): Need odd and >= 3 digits
middleThreeDigits(2002): Need odd and >= 3 digits
middleThreeDigits(-2002): Need odd and >= 3 digits
middleThreeDigits(0): Need odd and >= 3 digits
middleThreeDigits(-2147483648): Need odd and >= 3 digits
middleThreeDigits(2147483647): Need odd and >= 3 digits

Alternative Version

This longer version gives a stronger typed output, and it tries to be faster avoiding conversions to string. <lang d>import std.stdio, std.traits, std.math, std.variant;

/// Returns a string with the error, or the three digits. Algebraic!(string, char[3]) middleThreeDigits(T)(in T n) if (isIntegral!T) {

   // Awkward code to face abs(T.min) when T is signed.
   ulong ln;
   static if (isSigned!T) {
       if (n >= 0) {
           ln = n;
       } else {
           if (n == T.min) {
               ln = -(n + 1);
               ln++;
           } else {
               ln = -n;
           }
       }
   } else {
       ln = n;
   }
   if (ln < 100)
       return typeof(return)("n is too short.");
   immutable uint digits = 1 + cast(uint)log10(ln);
   if (digits % 2 == 0)
       return typeof(return)("n must have an odd number of digits.");
   // From the Reddit answer by "millstone".
   int drop = (digits - 3) / 2;
   while (drop-- > 0)
       ln /= 10;
   char[3] result = void;
   result[2] = ln % 10 + '0';
   ln /= 10;
   result[1] = ln % 10 + '0';
   ln /= 10;
   result[0] = ln % 10 + '0';
   return typeof(return)(result);

}

void main() {

   immutable passing = [123, 12345, 1234567, 987654321, 10001,
                        -10001, -123, -100, 100, -12345, -8765432];
   foreach (n; passing) {
       auto mtd = middleThreeDigits(n);
       // A string result means it didn't pass.
       assert(!mtd.peek!string);
       writefln("middleThreeDigits(%d): %s", n, mtd);
   }
   writeln();
   immutable failing = [1, 2, -1, -10, 2002, -2002, 0,
                        15, int.min, int.max];
   foreach (n; failing) {
       auto mtd = middleThreeDigits(n);
       assert(mtd.peek!string);
       writefln("middleThreeDigits(%d): %s", n, mtd);
   }
   writeln();
   immutable long[] passingL = [123, 12345, 1234567, 987654321, 10001,
                                -10001, -123, -100, 100, -12345,
                                -8765432, long.min, long.max];
   foreach (n; passingL) {
       auto mtd = middleThreeDigits(n);
       assert(!mtd.peek!string);
       writefln("middleThreeDigits(%d): %s", n, mtd);
   }
   writeln();
   immutable long[] failingL = [1, 2, -1, -10, 2002, -2002, 0, 15];
   foreach (n; failingL) {
       auto mtd = middleThreeDigits(n);
       assert(mtd.peek!string);
       writefln("middleThreeDigits(%d): %s", n, mtd);
   }
   writeln();
   {
       immutable n = short.min;
       auto mtd = middleThreeDigits(n);
       assert(!mtd.peek!string);
       writefln("middleThreeDigits(cast(short)%d): %s", n, mtd);
   }

}</lang>

Output:
middleThreeDigits(123): 123
middleThreeDigits(12345): 234
middleThreeDigits(1234567): 345
middleThreeDigits(987654321): 654
middleThreeDigits(10001): 000
middleThreeDigits(-10001): 000
middleThreeDigits(-123): 123
middleThreeDigits(-100): 100
middleThreeDigits(100): 100
middleThreeDigits(-12345): 234
middleThreeDigits(-8765432): 654

middleThreeDigits(1): n is too short.
middleThreeDigits(2): n is too short.
middleThreeDigits(-1): n is too short.
middleThreeDigits(-10): n is too short.
middleThreeDigits(2002): n must have an odd number of digits.
middleThreeDigits(-2002): n must have an odd number of digits.
middleThreeDigits(0): n is too short.
middleThreeDigits(15): n is too short.
middleThreeDigits(-2147483648): n must have an odd number of digits.
middleThreeDigits(2147483647): n must have an odd number of digits.

middleThreeDigits(123): 123
middleThreeDigits(12345): 234
middleThreeDigits(1234567): 345
middleThreeDigits(987654321): 654
middleThreeDigits(10001): 000
middleThreeDigits(-10001): 000
middleThreeDigits(-123): 123
middleThreeDigits(-100): 100
middleThreeDigits(100): 100
middleThreeDigits(-12345): 234
middleThreeDigits(-8765432): 654
middleThreeDigits(-9223372036854775808): 368
middleThreeDigits(9223372036854775807): 368

middleThreeDigits(1): n is too short.
middleThreeDigits(2): n is too short.
middleThreeDigits(-1): n is too short.
middleThreeDigits(-10): n is too short.
middleThreeDigits(2002): n must have an odd number of digits.
middleThreeDigits(-2002): n must have an odd number of digits.
middleThreeDigits(0): n is too short.
middleThreeDigits(15): n is too short.

middleThreeDigits(cast(short)-32768): 276

Erlang

<lang erlang>% Implemented by Arjun Sunel -module(middle_three_digits). -export([main/0]).

main() -> digits(123), digits(12345), digits(1234567), digits(987654321), digits(10001), digits(-10001), digits(-123), digits(-100), digits(100), digits(-12345), digits(1), digits(2), digits(-1), digits(-10), digits(2002), digits(-2002), digits(0).

digits(N) ->

if N < 0 -> digits(-N);

(N div 100) =:= 0 -> io:format("too small\n");

true -> K=length(integer_to_list(N)),

if (K rem 2) =:= 0 -> io:format("even number of digits\n"); true -> loop((K-3) div 2 , N) end

end.

loop(0,N) -> if N rem 1000 =:= 0 -> io:format("000\n");

N rem 1000 < 10 -> io:format("00~w~n",[N rem 1000]);

N rem 1000 < 100 -> io:format("0~w~n",[N rem 1000]); true -> io:format("~w~n", [N rem 1000]) end;

loop(X,N) when X>0 -> loop(X-1, N div 10). </lang>

Output:
123
234
345
654
000
000
123
100
100
234
too small
too small
too small
too small
even number of digits
even number of digits
too small
ok

FBSL

<lang qbasic>#APPTYPE CONSOLE

DIM numbers AS STRING = "123,12345,1234567,987654321,10001,-10001,-123,-100,100,-12345,1,2,-1,-10,2002,-2002,0" DIM dict[] = Split(numbers, ",") DIM num AS INTEGER DIM num2 AS INTEGER DIM powered AS INTEGER

FOR DIM i = 0 TO COUNT(dict) - 1

   num2 = dict[i]
   num = ABS(num2)
   IF num < 100 THEN
       display(num2, "is too small")
   ELSE
       FOR DIM j = 9 DOWNTO 1
           powered = 10 ^ j
           IF num >= powered THEN
               IF j MOD 2 = 1 THEN
                   display(num2, "has even number of digits")
               ELSE
                   display(num2, middle3(num, j))
               END IF
               EXIT FOR
           END IF
       NEXT
   END IF

NEXT

PAUSE

FUNCTION display(num, msg)

   PRINT LPAD(num, 11, " "), " --> ", msg

END FUNCTION

FUNCTION middle3(n, pwr)

   DIM power AS INTEGER = (pwr \ 2) - 1
   DIM m AS INTEGER = n
   m = m \ (10 ^ power)
   m = m MOD 1000
   IF m = 0 THEN
       RETURN "000"
   ELSE
       RETURN m
   END IF

END FUNCTION</lang> Output

        123 --> 123
      12345 --> 234
    1234567 --> 345
  987654321 --> 654
      10001 --> 000
     -10001 --> 000
       -123 --> 123
       -100 --> 100
        100 --> 100
     -12345 --> 234
          1 --> is too small
          2 --> is too small
         -1 --> is too small
        -10 --> is too small
       2002 --> has even number of digits
      -2002 --> has even number of digits
          0 --> is too small

Press any key to continue...

Fortran

Please find compilation instructions along with the output for the examples in the comments at the beginning of the file. This program was produced in an Ubuntu distribution of the GNU/linux system. <lang FORTRAN> !-*- mode: compilation; default-directory: "/tmp/" -*- !Compilation started at Sat Jun 1 14:48:41 ! !a=./f && make $a && OMP_NUM_THREADS=2 $a < unixdict.txt # some of the compilation options and redirection from unixdict.txt are vestigial. !gfortran -std=f2008 -Wall -fopenmp -ffree-form -fall-intrinsics -fimplicit-none f.f08 -o f ! 123 123 ! 12345 234 ! 1234567 345 ! 987654321 654 ! 10001 000 ! -10001 000 ! -123 123 ! -100 100 ! 100 100 ! -12345 234 ! 1 Too short ! 2 Too short ! -1 Too short ! -10 Too short ! 2002 Digit count too even ! -2002 Digit count too even ! 0 Too short ! !Compilation finished at Sat Jun 1 14:48:41


program MiddleMuddle

 integer, dimension(17) :: itest, idigits
 integer :: i, n
 data itest/123,12345,1234567,987654321,10001,-10001,-123,-100,100,-12345,1,2,-1,-10,2002,-2002,0/
 do i = 1, size(itest)
   call antibase(10, abs(itest(i)), idigits, n)
   write(6,'(i20,2x,a20)') itest(i), classifym3(idigits, n)
   if (0 .eq. itest(i)) exit
 end do

contains

 logical function even(n)
   integer, intent(in) :: n
   even = 0 .eq. iand(n,1)
 end function even
 function classifym3(iarray, n) result(s)
   integer, dimension(:), intent(in) :: iarray
   integer, intent(in) :: n
   character(len=20) :: s
   integer :: i,m
   if (n < 3) then
     s = 'Too short'
   else if (even(n)) then
     s = 'Digit count too even'
   else
     m = (n+1)/2
     write(s,'(3i1)')(iarray(i), i=m+1,m-1,-1)
   end if
 end function classifym3
 subroutine antibase(base, m, digits, n) ! digits ordered by increasing significance
   integer, intent(in) :: base, m
   integer, intent(out) :: n  ! the number of digits
   integer, dimension(:), intent(out) :: digits
   integer :: em
   em = m
   do n=1, size(digits)
     digits(n) = mod(em, base)
     em = em / base
     if (0 .eq. em) return
   end do
   stop 'antibase ran out of space to store result'
 end subroutine antibase

end program MiddleMuddle </lang>

Groovy

<lang groovy>def middleThree(Number number) {

   def text = Math.abs(number) as String
   assert text.size() >= 3 : "'$number' must be more than 3 numeric digits"
   assert text.size() % 2 == 1 : "'$number' must have an odd number of digits"
   int start = text.size() / 2 - 1
   text[start..(start+2)]

}</lang> Test Code: <lang groovy>[123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0].each { number ->

   def text = (number as String).padLeft(10)
   try {
       println "$text: ${middleThree(number)}"
   } catch(AssertionError error) {
       println "$text cannot be converted: $error.message"
   }

}</lang> Output:

       123: 123
     12345: 234
   1234567: 345
 987654321: 654
     10001: 000
    -10001: 000
      -123: 123
      -100: 100
       100: 100
    -12345: 234
         1 cannot be converted: '1' must be more than 3 numeric digits. Expression: (text.size() >= 3)
         2 cannot be converted: '2' must be more than 3 numeric digits. Expression: (text.size() >= 3)
        -1 cannot be converted: '-1' must be more than 3 numeric digits. Expression: (text.size() >= 3)
       -10 cannot be converted: '-10' must be more than 3 numeric digits. Expression: (text.size() >= 3)
      2002 cannot be converted: '2002' must have an odd number of digits. Expression: ((text.size() % 2) == 1)
     -2002 cannot be converted: '-2002' must have an odd number of digits. Expression: ((text.size() % 2) == 1)
         0 cannot be converted: '0' must be more than 3 numeric digits. Expression: (text.size() >= 3)

Haskell

<lang haskell>import Numeric

mid3 :: Integral a => a -> Either String String mid3 n | m < 100 = Left "is too small"

      |    even l = Left "has an even number of digits"
      | otherwise = Right . take 3 $ drop ((l-3) `div` 2) s
 where m = abs n
       s = showInt m ""
       l = length s

showMid3 :: Integer -> String showMid3 n = show n ++ ": " ++ either id id (mid3 n)

main :: IO () main = mapM_ (putStrLn . showMid3) [

 123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345,
 1, 2, -1, -10, 2002, -2002, 0]</lang>

Output:

123: 123
12345: 234
1234567: 345
987654321: 654
10001: 000
-10001: 000
-123: 123
-100: 100
100: 100
-12345: 234
1: is too small
2: is too small
-1: is too small
-10: is too small
2002: has an even number of digits
-2002: has an even number of digits
0: is too small

Icon and Unicon

The following solution works in both languages.

<lang unicon>procedure main(a)

  every n := !a do write(right(n,15)," -> ",midM(n))

end

procedure midM(n,m)

  /m := 3
  n := abs(n)
  return n ? if (*n >= m) then
                if (((*n-m) % 2) = 0) then (move((*n - m)/2),move(m))
                else "wrong number of digits"
             else "too short"

end</lang>

with output:

->m3d 123 12345 1234567 987654321 10001 -10001 -123 -100 100 -12345 1 2 -1 -10 2002 -2002 0
            123 -> 123
          12345 -> 234
        1234567 -> 345
      987654321 -> 654
          10001 -> 000
         -10001 -> 000
           -123 -> 123
           -100 -> 100
            100 -> 100
         -12345 -> 234
              1 -> too short
              2 -> too short
             -1 -> too short
            -10 -> too short
           2002 -> wrong number of digits
          -2002 -> wrong number of digits
              0 -> too short
->

J

Solution: <lang j>asString=: ":"0 NB. convert vals to strings getPfxSize=: [: -:@| 3 -~ # NB. get size of prefix to drop before the 3 middle digits getMid3=: (3 {. getPfxSize }. ,&'err') :: ('err'"_) NB. get 3 middle digits or return 'err' getMiddle3=: getMid3@asString@:|</lang> Example: <lang j> vals=: 123 12345 1234567 987654321 10001 _10001 _123 _100 100 _12345 1 2 _1 _10 2002 _2002 0

  getMiddle3 vals

123 234 345 654 000 000 123 100 100 234 err err err err err err err</lang>

Java

<lang Java>public class MiddleThreeDigits {

   public static void main(String[] args) {
       final long[] passing = {123, 12345, 1234567, 987654321, 10001, -10001,
           -123, -100, 100, -12345, Long.MIN_VALUE, Long.MAX_VALUE};
       final int[] failing = {1, 2, -1, -10, 2002, -2002, 0, Integer.MIN_VALUE,
           Integer.MAX_VALUE};
       for (long n : passing)
           System.out.printf("middleThreeDigits(%s): %s\n", n, middleThreeDigits(n));
       for (int n : failing)
           System.out.printf("middleThreeDigits(%s): %s\n", n, middleThreeDigits(n));
   }
   public static <T> String middleThreeDigits(T n) {
       String s = String.valueOf(n);
       if (s.charAt(0) == '-')
           s = s.substring(1);
       int len = s.length();
       if (len < 3 || len % 2 == 0)
           return "Need odd and >= 3 digits";
       int mid = len / 2;
       return s.substring(mid - 1, mid + 2);
   }

}</lang>

middleThreeDigits(123): 123
middleThreeDigits(12345): 234
middleThreeDigits(1234567): 345
middleThreeDigits(987654321): 654
middleThreeDigits(10001): 000
middleThreeDigits(-10001): 000
middleThreeDigits(-123): 123
middleThreeDigits(-100): 100
middleThreeDigits(100): 100
middleThreeDigits(-12345): 234
middleThreeDigits(-9223372036854775808): 368
middleThreeDigits(9223372036854775807): 368
middleThreeDigits(1): Need odd and >= 3 digits
middleThreeDigits(2): Need odd and >= 3 digits
middleThreeDigits(-1): Need odd and >= 3 digits
middleThreeDigits(-10): Need odd and >= 3 digits
middleThreeDigits(2002): Need odd and >= 3 digits
middleThreeDigits(-2002): Need odd and >= 3 digits
middleThreeDigits(0): Need odd and >= 3 digits
middleThreeDigits(-2147483648): Need odd and >= 3 digits
middleThreeDigits(2147483647): Need odd and >= 3 digits

JavaScript

<lang JavaScript>function middleThree(x){

 var n=+Math.abs(x); var l=n.length-1;
 if(l<2||l%2) throw new Error(x+': Invalid length '+(l+1));
 return n.slice(l/2-1,l/2+2);

}

[123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0].forEach(function(n){

 try{console.log(n,middleThree(n))}catch(e){console.error(e.message)}

});</lang>

123 "123"
12345 "234"
1234567 "345"
987654321 "654"
10001 "000"
-10001 "000"
-123 "123"
-100 "100"
100 "100"
-12345 "234"
1: Invalid length 1
2: Invalid length 1
-1: Invalid length 1
-10: Invalid length 2
2002: Invalid length 4
-2002: Invalid length 4
0: Invalid length 1

Julia

<lang julia>function middle(s) s = string(abs(s)) len = length(s) assert(len >= 3 && len % 2 == 1, "Number of digits must be odd and >= 3") mid = ifloor(len/2) return s[mid:mid+2] end passing = [123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345] failing = [1, 2, -1, -10, 2002, -2002, 0] for i in [passing,failing] try println("Number: $i ", "Answer: ",middle(i)) catch e println("Number: $i ", "Answer: ",e) end end</lang>

Number: 123 Answer: 123
Number: 12345 Answer: 234
Number: 1234567 Answer: 345
Number: 987654321 Answer: 654
Number: 10001 Answer: 000
Number: -10001 Answer: 000
Number: -123 Answer: 123
Number: -100 Answer: 100
Number: 100 Answer: 100
Number: -12345 Answer: 234
Number: 1 ErrorException("assertion failed: Number of digits must be odd and >= 3")
Number: 2 ErrorException("assertion failed: Number of digits must be odd and >= 3")
Number: -1 ErrorException("assertion failed: Number of digits must be odd and >= 3")
Number: -10 ErrorException("assertion failed: Number of digits must be odd and >= 3")
Number: 2002 ErrorException("assertion failed: Number of digits must be odd and >= 3")
Number: -2002 ErrorException("assertion failed: Number of digits must be odd and >= 3")
Number: 0 ErrorException("assertion failed: Number of digits must be odd and >= 3")

Lua

<lang lua>function middle_three(n) if n < 0 then n = -n end

n = tostring(n) if #n % 2 == 0 then return "Error: the number of digits is even." elseif #n < 3 then return "Error: the number has less than 3 digits." end

local l = math.floor(#n/2) return n:sub(l, l+2) end

-- test do local t = {123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0}

for _,n in pairs(t) do print(n, middle_three(n)) end end</lang>

Output:
123	123
12345	234
1234567	345
987654321	654
10001	000
-10001	000
-123	123
-100	100
100	100
-12345	234
1	Error: the number has less than 3 digits.
2	Error: the number has less than 3 digits.
-1	Error: the number has less than 3 digits.
-10	Error: the number is even.
2002	Error: the number is even.
-2002	Error: the number is even.
0	Error: the number has less than 3 digits.

Mathematica

<lang Mathematica>middleThree[n_Integer] :=

Block[{digits = IntegerDigits[n], len},
 len = Length[digits];
 If[len < 3 || EvenQ[len], "number digits odd or less than 3", 
  len = Ceiling[len/2]; 
  StringJoin @@ (ToString /@ digitslen - 1 ;; len + 1)]]

testData = {123, 12345, 1234567, 987654321, 10001, -10001, -123, -100,

   100, -12345, 1, 2, -1, -10, 2002, -2002, 0};

Column[middleThree /@ testData]</lang>

Output:

123 234 345 654 000 000 123 100 100 234 err: n too small err: n too small err: n too small err: n too small err: even number of digits err: even number of digits err: n too small

МК-61/52

<lang>П0 lg [x] 3 - x>=0 23 ИП0 1 0 / [x] ^ lg [x] 10^x П1 / {x} ИП1

  • БП 00 1 + x=0 29 ИП0 С/П 0

/</lang>

Instruction: enter the number in the РX (on display), the result after the execution of the same. In the case of an even or less than 3 number of digits the indicator displays an error message.

NetRexx

This sample goes the extra mile and provides a method that can display the middle N digits from the input value. To satisfy the requirements of this task, a static invocation of this general method is also provided with the value 3 hard coded as the digit count. <lang NetRexx>/* NetRexx */ options replace format comments java crossref symbols nobinary

sl = '123 12345 1234567 987654321 10001 -10001 -123 -100 100 -12345' -

    '1 2 -1 -10 2002 -2002 0' -
    'abc 1e3 -17e-3 4004.5 12345678 9876543210' -- extras

parse arg digsL digsR . if \digsL.datatype('w') then digsL = 3 if \digsR.datatype('w') then digsR = digsL if digsL > digsR then digsR = digsL

loop dc = digsL to digsR

 say 'Middle' dc 'characters'
 loop nn = 1 to sl.words()
   val = sl.word(nn)
   say middleDigits(dc, val)
   end nn
 say
 end dc

return

-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method middle3Digits(val) constant

 return middleDigits(3, val)

-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method middleDigits(digitCt, val) constant

 text = val.right(15)':'
 even = digitCt // 2 == 0 -- odd or even?
 select
   when digitCt <= 0                       then text = 'digit selection size must be >= 1'
   when \val.datatype('w')                 then text = text 'is not a whole number'
   when val.abs().length < digitCt         then text = text 'has less than' digitCt 'digits'
   when \even & val.abs().length // 2 == 0 then text = text 'does not have an odd number of digits'
   when even  & val.abs().length // 2 \= 0 then text = text 'does not have an even number of digits'
   otherwise do
     val = val.abs()
     valL = val.length
     cutP = (valL - digitCt) % 2
     text = text val.substr(cutP + 1, digitCt)
     end
   catch NumberFormatException
     text = val 'is not numeric'
   end
 return text

</lang> Output:

Middle 3 characters
            123: 123
          12345: 234
        1234567: 345
      987654321: 654
          10001: 000
         -10001: 000
           -123: 123
           -100: 100
            100: 100
         -12345: 234
              1: has less than 3 digits
              2: has less than 3 digits
             -1: has less than 3 digits
            -10: has less than 3 digits
           2002: does not have an odd number of digits
          -2002: does not have an odd number of digits
              0: has less than 3 digits
            abc: is not a whole number
            1e3: is not a whole number
         -17e-3: is not a whole number
         4004.5: is not a whole number
       12345678: does not have an odd number of digits
     9876543210: does not have an odd number of digits

OCaml

<lang ocaml>let even x = (x land 1) <> 1

let middle_three_digits x =

 let s = string_of_int (abs x) in
 let n = String.length s in
 if n < 3 then failwith "need >= 3 digits" else
 if even n then failwith "need odd number of digits" else
 String.sub s (n / 2 - 1) 3

let passing = [123; 12345; 1234567; 987654321; 10001; -10001; -123; -100; 100; -12345] let failing = [1; 2; -1; -10; 2002; -2002; 0]

let print x =

 let res =
   try (middle_three_digits x)
   with Failure e -> "failure: " ^ e
 in
 Printf.printf "%d: %s\n" x res

let () =

 print_endline "Should pass:";
 List.iter print passing;
 print_endline "Should fail:";
 List.iter print failing;
</lang>
Output:
Should pass:
123: 123
12345: 234
1234567: 345
987654321: 654
10001: 000
-10001: 000
-123: 123
-100: 100
100: 100
-12345: 234

Should fail:
1: failure: need >= 3 digits
2: failure: need >= 3 digits
-1: failure: need >= 3 digits
-10: failure: need >= 3 digits
2002: failure: need odd number of digits
-2002: failure: need odd number of digits
0: failure: need >= 3 digits

PARI/GP

This example is incorrect. Please fix the code and remove this message.

Details: Valid answers must always have three digits.

Works with: PARI/GP version 2.6.0

<lang parigp>middle(n)=my(v=digits(n));if(#v>2&&#v%2,100*v[#v\2]+10*v[#v\2+1]+v[#v\2+2],"no middle 3 digits"); apply(middle,[123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0])</lang> Output:

%1 = [123, 234, 345, 654, 0, 0, 123, 100, 100, 234, "no middle 3 digits", "no middle 3 digits", "no middle 3 digits", "no middle 3 digits", "no middle 3 digits", "no middle 3 digits", "no middle 3 digits"]

For earlier versions digits can be defined as <lang parigp>digits(n)=eval(Vec(Str(n)))</lang> or more efficiently as <lang parigp>digits(n)=Vec(apply(n->n-48,Vectorsmall(Str(n))))</lang>

Perl

<lang Perl>#!/usr/bin/perl use strict ; use warnings ;

sub middlethree {

  my $number = shift ;
  my $testnumber = abs $number ;
  my $error = "Middle 3 digits can't be shown" ;
  my $numberlength = length $testnumber ;
  if ( $numberlength < 3 ) {
     print "$error : $number too short!\n" ;
     return ;
  }
  if ( $numberlength % 2 == 0 ) {
     print "$error : even number of digits in $number!\n" ;
     return ;
  }
  my $middle = int ( $numberlength  / 2 ) ;
  print "Middle 3 digits of $number : " . substr( $testnumber , $middle - 1 , 3 ) . " !\n" ;
  return ;

}

my @numbers = ( 123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345 ,

     1, 2, -1, -10, 2002, -2002, 0 ) ;

map { middlethree( $_ ) } @numbers ; </lang>

Output:
Middle 3 digits of 123 : 123 !
Middle 3 digits of 12345 : 234 !
Middle 3 digits of 1234567 : 345 !
Middle 3 digits of 987654321 : 654 !
Middle 3 digits of 10001 : 000 !
Middle 3 digits of -10001 : 000 !
Middle 3 digits of -123 : 123 !
Middle 3 digits of -100 : 100 !
Middle 3 digits of 100 : 100 !
Middle 3 digits of -12345 : 234 !
Middle 3 digits can't be shown : 1 too short!
Middle 3 digits can't be shown : 2 too short!
Middle 3 digits can't be shown : -1 too short!
Middle 3 digits can't be shown : -10 too short!
Middle 3 digits can't be shown : even number of digits in 2002!
Middle 3 digits can't be shown : even number of digits in -2002!
Middle 3 digits can't be shown : 0 too short!

Perl 6

<lang Perl6>sub middle-three($n) {

   given $n.abs {
       when .chars < 3  { "$n is too short" }
       when .chars %% 2 { "$n has an even number of digits" }
       default          { "The three middle digits of $n are: ", .substr: (.chars - 3)/2, 3 }
   }

}

say middle-three($_) for <

   123 12345 1234567 987654321 10001 -10001 -123 -100 100 -12345
   1 2 -1 -10 2002 -2002 0

>;</lang>

Output:
The three middle digits of 123 are:  123
The three middle digits of 12345 are:  234
The three middle digits of 1234567 are:  345
The three middle digits of 987654321 are:  654
The three middle digits of 10001 are:  000
The three middle digits of -10001 are:  000
The three middle digits of -123 are:  123
The three middle digits of -100 are:  100
The three middle digits of 100 are:  100
The three middle digits of -12345 are:  234
1 is too short
2 is too short
-1 is too short
-10 is too short
2002 has an even number of digits
-2002 has an even number of digits
0 is too short

PureBasic

<lang purebasic>Procedure.s middleThreeDigits(x.q)

 Protected x$, digitCount
 If x < 0: x = -x: EndIf
 x$ = Str(x)
 digitCount = Len(x$)
 If digitCount < 3
   ProcedureReturn "invalid input: too few digits"
 ElseIf digitCount % 2 = 0
   ProcedureReturn "invalid input: even number of digits"
 EndIf
 ProcedureReturn Mid(x$,digitCount / 2, 3)

EndProcedure

If OpenConsole()

 Define testValues$ = "123 12345 1234567 987654321 10001 -10001 -123 -100 100 -12345 1 2 -1 -10 2002 -2002 0"
 
 Define i, value.q, numTests = CountString(testValues$, " ") + 1
 For i = 1 To numTests
   value = Val(StringField(testValues$, i, " "))
   PrintN(RSet(Str(value), 12, " ") + " : " + middleThreeDigits(value))
 Next
 
 Print(#crlf$ + #crlf$ + "Press ENTER to exit"): Input()
 CloseConsole()

EndIf</lang> Sample output:

         123 : 123
       12345 : 234
     1234567 : 345
   987654321 : 654
       10001 : 000
      -10001 : 000
        -123 : 123
        -100 : 100
         100 : 100
      -12345 : 234
           1 : invalid input: too few digits
           2 : invalid input: too few digits
          -1 : invalid input: too few digits
         -10 : invalid input: too few digits
        2002 : invalid input: even number of digits
       -2002 : invalid input: even number of digits
           0 : invalid input: too few digits

Python

<lang python>>>> def middle_three_digits(i): s = str(abs(i)) length = len(s) assert length >= 3 and length % 2 == 1, "Need odd and >= 3 digits" mid = length // 2 return s[mid-1:mid+2]

>>> passing = [123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345] >>> failing = [1, 2, -1, -10, 2002, -2002, 0] >>> for x in passing + failing: try: answer = middle_three_digits(x) except AssertionError as error: answer = error print("middle_three_digits(%s) returned: %r" % (x, answer))


middle_three_digits(123) returned: '123' middle_three_digits(12345) returned: '234' middle_three_digits(1234567) returned: '345' middle_three_digits(987654321) returned: '654' middle_three_digits(10001) returned: '000' middle_three_digits(-10001) returned: '000' middle_three_digits(-123) returned: '123' middle_three_digits(-100) returned: '100' middle_three_digits(100) returned: '100' middle_three_digits(-12345) returned: '234' middle_three_digits(1) returned: AssertionError('Need odd and >= 3 digits',) middle_three_digits(2) returned: AssertionError('Need odd and >= 3 digits',) middle_three_digits(-1) returned: AssertionError('Need odd and >= 3 digits',) middle_three_digits(-10) returned: AssertionError('Need odd and >= 3 digits',) middle_three_digits(2002) returned: AssertionError('Need odd and >= 3 digits',) middle_three_digits(-2002) returned: AssertionError('Need odd and >= 3 digits',) middle_three_digits(0) returned: AssertionError('Need odd and >= 3 digits',) >>> </lang>

Racket

<lang racket>

  1. lang racket

(define (middle x)

 (cond
   [(negative? x) (middle (- x))]
   [(< x 100)     "error: number too small"]
   [else 
    (define s (number->string x))
    (define l (string-length s))
    (cond [(even? l) "error: number has even length"]
          [else (define i (quotient l 2)) 
                (substring s (- i 1) (+ i 2))])]))

(map middle (list 123 12345 1234567 987654321 10001 -10001 -123 -100 100 -12345)) (map middle (list 1 2 -1 -10 2002 -2002 0)) </lang> The output: <lang racket> '("123" "234" "345" "654" "000" "000" "123" "100" "100" "234") '("error: number too small" "error: number too small" "error: number too small" "error: number too small"

 "error: number has even length" "error: number has even length" "error: number too small")

</lang>

REXX

version 1

<lang rexx>/* REXX ***************************************************************

  • 03.02.2013 Walter Pachl
  • 19.04.2013 mid 3 is now a function returning the middle 3 digits
  • or an error indication
                                                                                                                                            • /

sl='123 12345 1234567 987654321 10001 -10001 -123 -100 100 -12345',

  '2 -1 -10 2002 -2002 0 abc 1e3 -17e-3'

Do While sl<> /* loop through test values */

 Parse Var sl s sl                    /* pick next value            */
 Say left(s,12) '->' mid3(s)          /* test it                    */
 End

Exit

mid3: Procedure Parse arg d /* take the argument */ Select /* first test for valid input */

 When datatype(d)<>'NUM'   Then  Return 'not a number'
 When pos('E',translate(d))>0 Then  Return 'not just digits'
 When length(abs(d))<3     Then  Return 'less than 3 digits'
 When length(abs(d))//2<>1 Then  Return 'not an odd number of digits'
 Otherwise Do                         /* input is ok                */
   dx=abs(d)                          /* get rid of optional sign   */
   ld=length(dx)                      /* length of digit string     */
   z=(ld-3)/2                         /* number of digits to cut    */
   res=substr(dx,z+1,3)               /* get middle 3 digits        */
   End
 End
 Return res</lang>

Output:

123          -> 123
12345        -> 234
1234567      -> 345
987654321    -> 654
10001        -> 000
-10001       -> 000
-123         -> 123
-100         -> 100
100          -> 100
-12345       -> 234
2            -> less than 3 digits
-1           -> less than 3 digits
-10          -> less than 3 digits
2002         -> not an odd number of digits
-2002        -> not an odd number of digits
0            -> less than 3 digits
abc          -> not a number
1e3          -> not just digits
-17e-3       -> not just digits

version 2

A premise:   12.3e2   is an integer   (regardless of how it's displayed).
So is the value of a   googol   and a  googleplex.

This REXX version is limited to numbers whose absolute value ≤ 100,000 digits.
(The limit is defined via the   NUMERIC DIGITS   statement.) <lang rexx>/*REXX program returns the 3 middle digits of a number (or an error). */ n ='123 12345 1234567 987654321 10001 -10001 -123 -100 100 -12345',

  '2 -1 -10 2002 -2002 0 abc 1e3 -17e-3 1234567. 1237654.00',
  '1234567890123456789012345678901234567890123456789012345678901234567'
    do j=1  for words(n); z=word(n,j) /* [↓]  format the output nicely.*/
    say 'middle 3 digits of'  right(z,max(15,length(z))) '──►' middle3(z)
    end   /*j*/

exit /*stick a fork in it, we're done.*/ /*──────────────────────────────────MIDDLE3 subroutine──────────────────*/ middle3: procedure; arg x; numeric digits 1e5; er=' ***error!*** ' if datatype(x,'N') then x=abs(x)/1; L=length(x) if \datatype(x,'W') then return er "arg isn't an integer" if L<3 then return er "arg is less then three digits" if L//2==0 then return er "arg isn't an odd number of digits"

                         return  substr(x, (L-3)%2+1, 3)</lang>

output

middle 3 digits of             123 ──► 123
middle 3 digits of           12345 ──► 234
middle 3 digits of         1234567 ──► 345
middle 3 digits of       987654321 ──► 654
middle 3 digits of           10001 ──► 000
middle 3 digits of          -10001 ──► 000
middle 3 digits of            -123 ──► 123
middle 3 digits of            -100 ──► 100
middle 3 digits of             100 ──► 100
middle 3 digits of          -12345 ──► 234
middle 3 digits of               2 ──►     ***error!***  arg is less then three digits
middle 3 digits of              -1 ──►     ***error!***  arg is less then three digits
middle 3 digits of             -10 ──►     ***error!***  arg is less then three digits
middle 3 digits of            2002 ──►     ***error!***  arg isn't an odd number of digits
middle 3 digits of           -2002 ──►     ***error!***  arg isn't an odd number of digits
middle 3 digits of               0 ──►     ***error!***  arg is less then three digits
middle 3 digits of             abc ──►     ***error!***  arg isn't an integer
middle 3 digits of             1e3 ──►     ***error!***  arg isn't an odd number of digits
middle 3 digits of          -17e-3 ──►     ***error!***  arg isn't an integer
middle 3 digits of        1234567. ──► 345
middle 3 digits of      1237654.00 ──► 376
middle 3 digits of 1234567890123456789012345678901234567890123456789012345678901234567 ──► 345

Ruby

<lang ruby>def middle_three_digits(n)

  # minus sign doesn't factor into digit count,
  # and calling #abs acts as a duck-type assertion
  n = n.abs
  # convert to string and find length
  l = (s = n.to_s).length
  # check validity
  raise ArgumentError, "Number must have at least three digits" if l < 3
  raise ArgumentError, "Number must have an odd number of digits" if l % 2 == 0
  return s[l/2-1,3].to_i

end

samples = [

 123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345,
 1, 2, -1, -10, 2002, -2002, 0 

]

width = samples.map { |n| n.to_s.length }.max

samples.each do |n|

  print "%#{width}d: " % n
  begin
    puts "%03d" % middle_three_digits(n)
  rescue ArgumentError => e
    puts e.to_s
  end

end</lang> Output:

      123: 123
    12345: 234
  1234567: 345
987654321: 654
    10001: 000
   -10001: 000
     -123: 123
     -100: 100
      100: 100
   -12345: 234
        1: Number must have at least three digits
        2: Number must have at least three digits
       -1: Number must have at least three digits
      -10: Number must have at least three digits
     2002: Number must have an odd number of digits
    -2002: Number must have an odd number of digits
        0: Number must have at least three digits

Run BASIC

<lang runbasic>x$ = "123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0"

while word$(x$,i+1,",") <> ""

i	= i + 1
a1$	= trim$(word$(x$,i,","))
if left$(a1$,1) = "-" then a$ = mid$(a1$,2) else a$ = a1$
if (len(a$) and 1) = 0 or len(a$) < 3 then 
  print a1$;chr$(9);" length < 3 or is even"
 else
  print mid$(a$,((len(a$)-3)/2)+1,3);" ";a1$
end if

wend end</lang>

123 123
234 12345
345 1234567
654 987654321
000 10001
000 -10001
123 -123
100 -100
100 100
234 -12345
1	 length < 3 or is even
2	 length < 3 or is even
-1	 length < 3 or is even
-10	 length < 3 or is even
2002	 length < 3 or is even
-2002	 length < 3 or is even
0	 length < 3 or is even

Rust

<lang rust>fn middle_three_digits(x: int) -> Result<~str, ~str> {

   let s = int::abs(x).to_str();
   let len = s.len();
   if len < 3 {
       Err(~"Too short")
   } else if len % 2 == 0 {
       Err(~"Even number of digits")
   } else {
       Ok(s.slice(len/2 - 1, len/2 + 2))
   }

}

fn print_result(x: int) {

   io::print(fmt!("middle_three_digits(%?) returned: ", x));
   match middle_three_digits(x) {
       Ok(move s) => io::println(fmt!("Success, %s", s)),
       Err(move s) => io::println(fmt!("Failure, %s", s))
   }

}

fn main() {

   let passing = [123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345];
   let failing = [1, 2, -1, -10, 2002, -2002, 0];
   for passing.each |i| {
       print_result(*i);
   }
   for failing.each |i| {
       print_result(*i);
   }

}</lang>

Output:

middle_three_digits(123) returned: Success, 123
middle_three_digits(12345) returned: Success, 234
middle_three_digits(1234567) returned: Success, 345
middle_three_digits(987654321) returned: Success, 654
middle_three_digits(10001) returned: Success, 000
middle_three_digits(-10001) returned: Success, 000
middle_three_digits(-123) returned: Success, 123
middle_three_digits(-100) returned: Success, 100
middle_three_digits(100) returned: Success, 100
middle_three_digits(-12345) returned: Success, 234
middle_three_digits(1) returned: Failure, Too short
middle_three_digits(2) returned: Failure, Too short
middle_three_digits(-1) returned: Failure, Too short
middle_three_digits(-10) returned: Failure, Too short
middle_three_digits(2002) returned: Failure, Even number of digits
middle_three_digits(-2002) returned: Failure, Even number of digits
middle_three_digits(0) returned: Failure, Too short

Scala

<lang scala>/**

* Optionally return the middle three digits of an integer.
*
* @example List(123,12345,-789,1234,12) flatMap (middleThree(_)), returns: List(123, 234, 789)
*/

def middleThree( s:Int ) : Option[Int] = s.abs.toString match {

 case v if v.length % 2 == 0   => None   // Middle three is undefined for even lengths
 case v if v.length < 3        => None
 case v                        => 			
   val i = (v.length / 2) - 1
   Some( v.substring(i,i+3).toInt )

}


// A little test... val intVals = List(123,12345,1234567,987654321,10001,-10001,-123,-100,100,-12345,1,2,-1,-10,2002,-2002,0)

intVals map (middleThree(_)) map {

 case None => "No middle three" 
 case Some(v) => "%03d".format(v)  // Format the value, force leading zeroes 

} mkString("\n") </lang>

Output:
123
234
345
654
000
000
123
100
100
234
No middle three
No middle three
No middle three
No middle three
No middle three
No middle three
No middle three

Tcl

<lang tcl>proc middleThree n {

   if {$n < 0} {

set n [expr {-$n}]

   }
   set idx [expr {[string length $n] - 2}]
   if {$idx % 2 == 0} {

error "no middle three digits: input is of even length"

   }
   if {$idx < 1} {

error "no middle three digits: insufficient digits"

   }
   set idx [expr {$idx / 2}]
   string range $n $idx [expr {$idx+2}]

}</lang> Demonstrating: <lang tcl>foreach n {

   123 12345 1234567 987654321 10001 -10001 -123 -100 100 -12345
   1 2 -1 -10 2002 -2002 0

} {

   if {[catch {

set mid [middleThree $n]

   } msg]} then {

puts "error for ${n}: $msg"

   } else {

puts "found for ${n}: $mid"

   }

}</lang>

Output:
found for 123: 123
found for 12345: 234
found for 1234567: 345
found for 987654321: 654
found for 10001: 000
found for -10001: 000
found for -123: 123
found for -100: 100
found for 100: 100
found for -12345: 234
error for 1: no middle three digits: insufficient digits
error for 2: no middle three digits: insufficient digits
error for -1: no middle three digits: insufficient digits
error for -10: no middle three digits: input is of even length
error for 2002: no middle three digits: input is of even length
error for -2002: no middle three digits: input is of even length
error for 0: no middle three digits: insufficient digits

UNIX Shell

Works with: Bourne Again Shell
Works with: Korn Shell version 93
Works with: Z Shell

<lang bash>function middle3digits {

 typeset -i n="${1#-}"
 typeset -i l=${#n}
 if (( l < 3 )); then
   echo >&2 "$1 has less than 3 digits"
   return 1
 elif (( l % 2 == 0 )); then
   echo >&2 "$1 has an even number of digits"
   return 1
 else
   echo ${n:$((l/2-1)):3}
   return 0
 fi

}

  1. test

testdata=(123 12345 1234567 987654321 10001 -10001 -123 -100 100 -12345 1 2 -1

         -10 2002 -2002 0)

for n in ${testdata[@]}; do

 printf "%10d: " $n
 middle3digits "$n"

done</lang>

Output:

       123: 123
     12345: 234
   1234567: 345
 987654321: 654
     10001: 000
    -10001: 000
      -123: 123
      -100: 100
       100: 100
    -12345: 234
         1: 1 has less than 3 digits
         2: 2 has less than 3 digits
        -1: -1 has less than 3 digits
       -10: -10 has less than 3 digits
      2002: 2002 has an even number of digits
     -2002: -2002 has an even number of digits
         0: 0 has less than 3 digits

Vedit macro language

<lang vedit>do {

   #1 = Get_Num("Enter a number, or 0 to stop: ", STATLINE)
   Ins_Text("Input: ") Num_Ins(#1, COUNT, 10)
   Call("MIDDLE_3_DIGITS")
   Ins_Text("  Result: ") Reg_Ins(10) Ins_Newline
   Update()

} while (#1); Return

// Find middle 3 digits of a number // in: #1 = numeric value // out: @10 = the result, or error text //

MIDDLE_3_DIGITS:

Buf_Switch(Buf_Free) Num_Ins(abs(#1), LEFT+NOCR) // the input value as string

  1. 2 = Cur_Col-1 // #2 = number of digits

if (#2 < 3) {

   Reg_Set(10, "Too few digits!")

} else {

   if ((#2 & 1) == 0) {

Reg_Set(10, "Not odd number of digits!")

   } else {

Goto_Pos((#2-3)/2) Reg_Copy_Block(10, Cur_Pos, Cur_Pos+3)

   }

} Buf_Quit(OK) Return </lang>

Output:

Input:        123  Result: 123
Input:      12345  Result: 234
Input:    1234567  Result: 345
Input:  987654321  Result: 654
Input:      10001  Result: 000
Input:     -10001  Result: 000
Input:       -123  Result: 123
Input:       -100  Result: 100
Input:        100  Result: 100
Input:     -12345  Result: 234
Input:          1  Result: Too few digits!
Input:          2  Result: Too few digits!
Input:         -1  Result: Too few digits!
Input:        -10  Result: Too few digits!
Input:       2002  Result: Not odd number of digits!
Input:      -2002  Result: Not odd number of digits!
Input:          0  Result: Too few digits! 

XPL0

<lang XPL0>include c:\cxpl\stdlib;

func Mid3Digits(I); \Return the middle three digits of I int I; int Len, Mid; char S(10); [ItoA(abs(I), S); Len:= StrLen(S); if Len<3 or (Len&1)=0 then return "Must be 3, 5, 7 or 9 digits"; Mid:= Len/2; S:= S + Mid - 1; S(2):= S(2) ! $80; \terminate string return S; \WARNING: very temporary ];

int Passing, Failing, X; [Passing:= [123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345];

Failing:= [1, 2, -1, -10, 2002, -2002, 0];     \WARNING: nasty trick

for X:= 0 to 16 do

   [Text(0, "Middle three digits of ");  IntOut(0, Passing(X));
    Text(0, " returned: ");
    Text(0, Mid3Digits(Passing(X)));  CrLf(0);
   ];

]</lang>

Output:
Middle three digits of 123 returned: 123
Middle three digits of 12345 returned: 234
Middle three digits of 1234567 returned: 345
Middle three digits of 987654321 returned: 654
Middle three digits of 10001 returned: 000
Middle three digits of -10001 returned: 000
Middle three digits of -123 returned: 123
Middle three digits of -100 returned: 100
Middle three digits of 100 returned: 100
Middle three digits of -12345 returned: 234
Middle three digits of 1 returned: Must be 3, 5, 7 or 9 digits
Middle three digits of 2 returned: Must be 3, 5, 7 or 9 digits
Middle three digits of -1 returned: Must be 3, 5, 7 or 9 digits
Middle three digits of -10 returned: Must be 3, 5, 7 or 9 digits
Middle three digits of 2002 returned: Must be 3, 5, 7 or 9 digits
Middle three digits of -2002 returned: Must be 3, 5, 7 or 9 digits
Middle three digits of 0 returned: Must be 3, 5, 7 or 9 digits