33
\$\begingroup\$

Challenge

Given an integer \$Q\$ in the range \$-2^{100} ≤ Q ≤ 2^{100}\$, output the number of digits in that number (in base 10).

Rules

Yes, you may take the number as a string and find its length.

All mathematical functions are allowed.

You may take input in any base, but the output must be the length of the number in base 10.

Do not count the minus sign for negative numbers. The number will never have a decimal point.

Zero can either have one or zero digits.

Assume the input will always be a valid integer.

Examples

Input > Output

-45 > 2
12548026 > 8
33107638153846291829 > 20
-20000 > 5
0 > 1 or 0

Winning

Shortest code in bytes wins.

\$\endgroup\$
0

81 Answers 81

46
\$\begingroup\$

Taxi, 1118 bytes

1 is waiting at Starchild Numerology.Go to Post Office:w 1 l 1 r 1 l.Pickup a passenger going to Chop Suey.Go to Chop Suey:n 1 r 1 l 4 r 1 l.Pickup a passenger going to Crime Lab.'-' is waiting at Writer's Depot.Go to Writer's Depot:n 1 l 3 l.Pickup a passenger going to Crime Lab.Go to Crime Lab:n 1 r 2 r 2 l.Switch to plan "n" if no one is waiting.-1 is waiting at Starchild Numerology.[n]0 is waiting at Starchild Numerology.Go to Starchild Numerology:s 1 r 1 l 1 l 2 l.Pickup a passenger going to Cyclone.Pickup a passenger going to Addition Alley.Go to Cyclone:e 1 l 2 r.[r]Pickup a passenger going to Cyclone.Pickup a passenger going to Addition Alley.Go to Zoom Zoom:n.Go to Addition Alley:w 1 l 1 r.Pickup a passenger going to Addition Alley.Go to Chop Suey:n 1 r 2 r.Switch to plan "f" if no one is waiting.Pickup a passenger going to Sunny Skies Park.Go to Sunny Skies Park:n 1 l 3 l 1 l.Go to Cyclone:n 1 l.Switch to plan "r".[f]Go to Addition Alley:n 1 l 2 l.Pickup a passenger going to The Babelfishery.Go to The Babelfishery:n 1 r 1 r.Pickup a passenger going to Post Office.Go to Post Office:n 1 l 1 r.

Try it online!

Ungolfed:

1 is waiting at Starchild Numerology.
Go to Post Office: west 1st left 1st right 1st left.
Pickup a passenger going to Chop Suey.
Go to Chop Suey: north 1st right 1st left 4th right 1st left.
Pickup a passenger going to Crime Lab.
'-' is waiting at Writer's Depot.
Go to Writer's Depot: north 1st left 3rd left.
Pickup a passenger going to Crime Lab.
Go to Crime Lab: north 1st right 2nd right 2nd left.
Switch to plan "n" if no one is waiting.
-1 is waiting at Starchild Numerology.
[n]
0 is waiting at Starchild Numerology.
Go to Starchild Numerology: south 1st right 1st left 1st left 2nd left.
Pickup a passenger going to Cyclone.
Pickup a passenger going to Addition Alley.
Go to Cyclone: east 1st left 2nd right.
[r]
Pickup a passenger going to Cyclone.
Pickup a passenger going to Addition Alley.
Go to Zoom Zoom: north.
Go to Addition Alley: west 1st left 1st right.
Pickup a passenger going to Addition Alley.
Go to Chop Suey: north 1st right 2nd right.
Switch to plan "f" if no one is waiting.
Pickup a passenger going to Sunny Skies Park.
Go to Sunny Skies Park: north 1st left 3rd left 1st left.
Go to Cyclone: north 1st left.
Switch to plan "r".
[f]
Go to Addition Alley: north 1st left 2nd left.
Pickup a passenger going to The Babelfishery.
Go to The Babelfishery: north 1st right 1st right.
Pickup a passenger going to Post Office.
Go to Post Office: north 1st left 1st right.

Explanation:

Pickup the input and split it into individual characters
Pickup the value 1.
If the first character a hyphen, add -1. Otherwise, add 0.
Keep picking up characters and adding 1 until you're out.
Convert the running total to a string and print to stdout.
\$\endgroup\$
7
  • 9
    \$\begingroup\$ I've been a lurker in this exchange for a long time, but have never seen something like this \$\endgroup\$ Commented May 17, 2017 at 0:35
  • 7
    \$\begingroup\$ Will this run out of gas if the number is long enough? \$\endgroup\$ Commented May 17, 2017 at 8:58
  • 5
    \$\begingroup\$ This is a bigger brainfuck than brainfuck. \$\endgroup\$
    – Saturn
    Commented May 17, 2017 at 11:43
  • 1
    \$\begingroup\$ @RobertFraser That's why we stop at Zoom Zoom in every loop of plan "r". I just tested it up to 100,000 digits and it never ran out of gas. I didn't calculate it but I suppose it takes in more than enough fare to pay for the gas it's using so it fills up the tank on every loop. \$\endgroup\$ Commented May 17, 2017 at 12:21
  • 1
    \$\begingroup\$ @CupofJava OH MY GOSH how did I forget about Shakespeare. \$\endgroup\$ Commented May 17, 2017 at 16:09
21
\$\begingroup\$

Mathematica, 13 bytes

IntegerLength

There's a built-in... returns 0 for 0.

\$\endgroup\$
3
  • 2
    \$\begingroup\$ Mathematica prevails :D \$\endgroup\$
    – Beta Decay
    Commented May 16, 2017 at 20:03
  • 1
    \$\begingroup\$ not in code golf it doesn't :) \$\endgroup\$ Commented May 16, 2017 at 20:16
  • 12
    \$\begingroup\$ There's a built-in: When isn't there? \$\endgroup\$ Commented May 17, 2017 at 14:56
17
\$\begingroup\$

dc, 3

?Zp

Note that normally dc requires negative numbers to be given with _ instead of the more usual -. However, in this case, either may be used. If - is given, then dc treats this as a subtraction on an empty stack, throws dc: stack empty, and then continues with the rest of the number; Thus the result is no different.

Try it online.

?    # input
 Z   # measure length
  p  # print
\$\endgroup\$
1
  • \$\begingroup\$ Couldn't this just be Z as a function submission? dc's a concatenative language with quote+dup+eval operators, it can therefore reuse arbitrary strings of code. \$\endgroup\$
    – user62131
    Commented May 17, 2017 at 8:02
14
\$\begingroup\$

Brachylog, 1 byte

l

Try it online!

Another builtin solution, but this one has the shortest name (unless someone finds a language which does this task in zero bytes). This should work in both Brachylog 1 and Brachylog 2.

This is a function submission (the TIO link contains a command-line argument that causes the interpreter to run an individual function rather than a whole program), partly because otherwise we'd have to spend bytes on output, partly because Brachylog's syntax for negative numbers is somewhat unusual and making this program a function resolves any potential arguments about input syntax.

It's often bothered me that most of Brachylog's builtins treat negative numbers like positive ones, but that fact ended up coming in handy here. I guess there are tradeoffs involved with every golfing language.

\$\endgroup\$
1
  • 1
    \$\begingroup\$ This is where I stop scrolling... this is outrageous! \$\endgroup\$ Commented May 18, 2017 at 13:46
14
\$\begingroup\$

Retina, 2 bytes

\d

Try it online!

Retina doesn't really know what numbers are, so the input is treated as a string and we simply count the digit characters.

\$\endgroup\$
0
6
\$\begingroup\$

05AB1E, 2 bytes

Äg

Try it online! or Try All Tests!

Ä  # Absolute value
 g # Length
\$\endgroup\$
3
  • 1
    \$\begingroup\$ Ä, huh? Not þ? Fair enough. \$\endgroup\$ Commented May 16, 2017 at 19:42
  • \$\begingroup\$ @carusocomputing I thought of Ä first, but þ would handle a decimal point, so it's a little better I guess. \$\endgroup\$
    – Riley
    Commented May 16, 2017 at 19:43
  • \$\begingroup\$ Just cool how 2 people came up with 2 different 2 byte solutions within 2 minutes of each other, I don't think there's a third though; trying to think of one. \$\endgroup\$ Commented May 16, 2017 at 19:45
6
\$\begingroup\$

Alice, 16 bytes

//; 'q<)e
o!@i -

Try it online!

Explanation

Finding a half-decent layout for this was quite tricky. I'm still not super happy with it because of the spaces, the < and the ;, but this is the best I could do for now.

String length is one of those very common built-ins that doesn't exist in Alice, because its input is a string and its output is an integer (and all Alice commands are strictly integers to integer or strings to strings). We can measure a string's length by writing it to the tape in Ordinal mode and then finding its end in Cardinal mode.

/      Reflect to SE. Switch to Ordinal. While in Ordinal mode, the IP will bounce
       diagonally up and down through the code.
!      Store an implicit empty string on the tape, does nothing.
;      Discard an implicit empty string, does nothing.
i      Read all input as a string.
'-     Push "-".
<      Set the horizontal component of the IP's direction to west, so we're bouncing
       back now.
-      Remove substring. This deletes the minus sign if it exists.
'i     Push "i".
;      Discard it again.
!      Store the input, minus a potential minus sign, on the tape.
/      Reflect to W. Switch to Cardinal. The IP immediately wraps to the
       last column.
e)     Search the tape to the right for a -1, which will be found at the end
       of the string we stored there.
<      Does nothing.
q      Push the tape head's position, which is equal to the string length.
'<sp>  Push " ".
;      Discard it again.
/      Reflect to NW. Switch to Ordinal. The IP immediately bounces off
       the top boundary to move SW instead.
o      Implicitly convert the string length to a string and print it.
       IP bounces off the bottom left corner, moves back NE.
/      Reflect to S. Switch to Cardinal.
!      Store an implicit 0 on the tape, irrelevant.
       The IP wraps back to the first line.
/      Reflect to NE. Switch to Ordinal. The IP immediately bounces off
       the top boundary to move SE instead.
@      Terminate the program.

I also tried taking care of the minus sign in Cardinal mode with H (absolute value), but the additional mode switch always ended up being more expensive in my attempts.

\$\endgroup\$
6
\$\begingroup\$

brainfuck, 37 bytes

-[+>+[+<]>+]>->,[-<->]<[>+>],[<+>,]<.

Output is by byte value.

Try it online!

Explanation

-[+>+[+<]>+]>->  Constant for 45 (from esolangs wiki)
,                Read a byte of input
[-<->]           Subtract that byte from 45
<[>+>]           If the result is nonzero then increment a cell and move to the right
                 (0 means it was a minus; so not counted)
,[<+>,]          Read a byte and increment the cell to its left until EOF is reached
<.               Print the cell that was being incremented
\$\endgroup\$
3
  • \$\begingroup\$ Is it possible to add a footer to the TIO link which outputs the result as a number? \$\endgroup\$
    – Beta Decay
    Commented May 18, 2017 at 18:36
  • \$\begingroup\$ @BetaDecay Added \$\endgroup\$ Commented May 18, 2017 at 18:42
  • \$\begingroup\$ That's brilliant, thanks :D \$\endgroup\$
    – Beta Decay
    Commented May 18, 2017 at 19:52
6
\$\begingroup\$

GNU AWK, 18 17 15 bytes

$1=gsub(/\w/,1)

Substitutes every number character (except for the minus sign) alphanumeric character of the input for another character (here, the number 1), and assigns the number of substitutions to the output.

Thanks for cnamejj and manatwork for helping me saving some bytes!

Try it online!

AWK, 17 bytes

$1=gsub(/[^-]/,1)

This is a previous answer, that should work on any Awk version, not only GNU's.

Try it online!

\$\endgroup\$
7
  • 1
    \$\begingroup\$ Welcome to Code Golf, nice first answer! \$\endgroup\$
    – rydwolf
    Commented Dec 20, 2020 at 21:30
  • 1
    \$\begingroup\$ You could use gsub(".",1) to knock off a few more characters too. Nice idea for how to do this BTW. \$\endgroup\$
    – cnamejj
    Commented Dec 20, 2020 at 21:35
  • 1
    \$\begingroup\$ Thanks, guys! @cnamejj I could not make this work with negative numbers. \$\endgroup\$ Commented Dec 20, 2020 at 21:41
  • 1
    \$\begingroup\$ @cnamejj you have just gave me an idea to regex every character, but the minus sign. I'll save one byte. \$\endgroup\$ Commented Dec 20, 2020 at 22:00
  • 1
    \$\begingroup\$ Although there is no \d in AWK, we still have \w (at least in gawk, but not in mawk), which is good enough in this case. \$\endgroup\$
    – manatwork
    Commented Dec 20, 2020 at 22:21
5
\$\begingroup\$

PHP, 23 Bytes

<?=-~log10(abs($argn));

Try it online!

log of base 10 of the absolute value plus one cast to int

for zero as input log10 gives back INF which is interpreted as false

The better way is to replace $argn with $argn?:1 +3 Bytes

PHP, 27 Bytes

<?=strlen($argn)-($argn<0);

string length minus boolean is lower then zero

+2 Bytes for string comparision $argn<"0"

Try it online!

PHP, 32 Bytes

<?=preg_match_all("#\d#",$argn);

Try it online!

Regex count all digits

35 Bytes

<?=strlen($argn)-strspn($argn,"-");

Try it online!

string length minus count -

strspn

\$\endgroup\$
8
  • 1
    \$\begingroup\$ The first one doesn't work, for example, for 10, because ^ has lower priority. You can fix it with -~. \$\endgroup\$
    – user63956
    Commented May 17, 2017 at 5:36
  • \$\begingroup\$ Why not simply <?=strlen(abs($argn)); ? \$\endgroup\$
    – roberto06
    Commented May 17, 2017 at 8:38
  • \$\begingroup\$ @user63956 The version with log10 can't work in cases of input zero so I delete it. \$\endgroup\$ Commented May 17, 2017 at 10:01
  • 1
    \$\begingroup\$ @JörgHülsermann Why not just $argn?:1? It would be 26 bytes with log10() and abs(). \$\endgroup\$
    – user63956
    Commented May 17, 2017 at 10:51
  • 1
    \$\begingroup\$ @JörgHülsermann -~$x is equivalent to ((int)$x)+1. <?=-~log10(abs($argn?:1)); seems to work. \$\endgroup\$
    – user63956
    Commented May 17, 2017 at 11:24
5
\$\begingroup\$

Fortran 95 (gfortran), 121 96 95 bytes

program c
character b
call get_command_argument(1,b,length=i)
print*,i-index(b,'-')
end program

Explanation:
Subtracts the index of the '-' sign from the length of the argument.
Arrays start at 1 in Fortran, and index() returns 0 if symbol not found.

Edit: Switched to implicit integer "i", also consolidated argument getter.

Edit: -1 byte thanks to @Tsathoggua

\$\endgroup\$
1
  • 1
    \$\begingroup\$ Welcome to PPCG! \$\endgroup\$ Commented May 17, 2017 at 14:48
4
\$\begingroup\$

Ruby, 15 11+1 = 16 12 bytes

Uses the -n flag.

p~/$/-~/\d/

Try it online!

Explanation

                  # -n flag gets one line of input implicitly
p                 # Print
 ~/$/             # Position of end of line (aka string length) in input
     -            # minus
      ~/\d/       # Position of first digit (1 if negative number, 0 otherwise)
\$\endgroup\$
2
  • 1
    \$\begingroup\$ What magic is this? \$\endgroup\$
    – Chowlett
    Commented May 17, 2017 at 15:51
  • 2
    \$\begingroup\$ @Chowlett added an explanation. \$\endgroup\$
    – Value Ink
    Commented May 17, 2017 at 19:39
3
\$\begingroup\$

PowerShell, 24 Bytes

"$args"-replace'-'|% Le*

casts the "absolute" value of the input args to a string and gets the 'length' property of it.

1 byte shorter than "".Length

until someone finds a better way to get the abs of a number in PS this is probably as short as it will get.

\$\endgroup\$
1
  • 1
    \$\begingroup\$ How about "$args".trim('-')|% Le* ? :) \$\endgroup\$
    – whatever
    Commented May 17, 2017 at 9:20
3
\$\begingroup\$

05AB1E, 2 bytes

þg

Try it online!

   # Implicit input [a]...
þ  # Only the digits in [a]...
 g # length of [a]...
   # Implicit output.
\$\endgroup\$
0
3
\$\begingroup\$

Perl 5, 9 + 1 = 10 bytes

$_=y/-//c

Try it online!

Run with -p (1 byte penalty).

Explanation

$_=y/-//c
            {implicit from -p: for each line of input}
   y/ //    In {the input}, replace
        c     everything except
     -        '-'
$_=         Store number of replacements back in $_
            {implicit from -p: output $_}

We treat the input as a string in order to handle numbers outside the 64-bit range. One interesting trick here is that we don't have to specify what we're replacing the nonhyphens with; we can still count the number of replacements that occur.

The TIO link uses -l in order to let us run the program on multiple data without the newlines between them interfering. If the program only has to run once, we can do without it, so long as there's no final newline on the input.

\$\endgroup\$
3
\$\begingroup\$

V (vim), 20 bytes

:s/-
C<C-r>=strlen(<C-r>")
<esc>

Try it online!

Remove minuses(if any), cut the line, and get its length.

Not sure if I need the <esc> at the end.

\$\endgroup\$
1
  • \$\begingroup\$ I don't think you need the final <esc>, at that point the solution is there, no need to exit from insert mode \$\endgroup\$
    – Leo
    Commented Apr 11, 2021 at 22:29
2
\$\begingroup\$

Jelly, 2 bytes

DL

Try it online!

This does literally what was asked:

DL - Main link number n         e.g. -45
D  - convert to a decimal list       [-4,-5]
 L - get the length                  2
\$\endgroup\$
4
  • \$\begingroup\$ That's an interesting built-in there, does D work on decimals? Would -1.2 output [-1,-0.2]? Tried it myself, it does not. \$\endgroup\$ Commented May 16, 2017 at 19:43
  • 1
    \$\begingroup\$ Not quite, the base conversion only goes down to the units so, for example, 654.321D would yield [6,5,4.321] (well actually [6.0,5.0,4.321000000000026]) \$\endgroup\$ Commented May 16, 2017 at 19:45
  • \$\begingroup\$ [-6.0, -5.0, -4.321000000000026], actually, apparently. \$\endgroup\$ Commented May 16, 2017 at 19:46
  • \$\begingroup\$ Ah - yeah just edited - floating point arithmetic. \$\endgroup\$ Commented May 16, 2017 at 19:47
2
\$\begingroup\$

Python 2, 31 22 bytes

-9 bytes thanks to Rod.

lambda i:len(`abs(i)`)

Try it online!

\$\endgroup\$
2
  • 1
    \$\begingroup\$ len(`abs(s)`) with number as input is shorter \$\endgroup\$
    – Rod
    Commented May 16, 2017 at 19:39
  • 3
    \$\begingroup\$ Too bad Python doesn't have function composition. It would be just len∘repr∘abs. \$\endgroup\$ Commented May 17, 2017 at 16:13
2
\$\begingroup\$

CJam, 5 bytes

q'--,

String based.

Try it online!

9 bytes for a purely math-based solution:

riz)AmLm]

Or another 5 with base conversion:

riAb,
\$\endgroup\$
1
  • \$\begingroup\$ Or also 5: rizs,. \$\endgroup\$ Commented May 16, 2017 at 19:42
2
\$\begingroup\$

Brain-Flak, 63 bytes

([({})]((((()()()()())){}{})){}{})((){[()](<{}>)}{})([{}][]<>)

Try it online!

This is 62 bytes of code and +1 byte for the -a flag.

I tried two other approaches, but unfortunately both of them were longer:

([]<({}[((((()()()()())){}{})){}{}]<>)((){[()](<{}>)}{})>)({}[{}])

([]<>)<>({}<>)((((([][]())){}{})){}{}[{}])((){[()](<{}>)}{})([{}]{})

This should be a very short answer. In fact, if we didn't have to support negative numbers, we could just do:

([]<>)

But we have to compare the first input with 45 (ASCII -) first, which is most of the byte count of this answer.

An arithmetic solution might be shorter.

\$\endgroup\$
3
  • \$\begingroup\$ I count 62 bytes..? \$\endgroup\$ Commented May 16, 2017 at 20:44
  • 1
    \$\begingroup\$ @totallyhuman see my edit. \$\endgroup\$
    – DJMcMayhem
    Commented May 16, 2017 at 20:55
  • \$\begingroup\$ 49 bytes: ([{}]((((()()()()())){}{})){}{})({(<()>)}{}[]<>) \$\endgroup\$
    – Nitrodon
    Commented May 17, 2017 at 1:40
2
\$\begingroup\$

Japt, 5 bytes

a s l

Try it online!

Explanation

 a s l
Ua s l
Ua     # take the absolute value of the input
   s   # and turn it into a string
     l # and return its length
\$\endgroup\$
2
\$\begingroup\$

Ruby, 20 bytes

->a{a.abs.to_s.size}
\$\endgroup\$
3
  • \$\begingroup\$ FYI: in order to call it you do: ->a{a.abs.to_s.size}[-95] \$\endgroup\$ Commented May 18, 2017 at 9:36
  • \$\begingroup\$ or just classic way - ->a{a.abs.to_s.size}.call(-92) \$\endgroup\$
    – marmeladze
    Commented May 18, 2017 at 9:38
  • 2
    \$\begingroup\$ not a golfy way :D \$\endgroup\$ Commented May 18, 2017 at 9:39
2
\$\begingroup\$

RProgN 2, 2 bytes

âL

Try it online!

Simply gets the absolute value of the input, and counts the digits.

\$\endgroup\$
2
\$\begingroup\$

Pyth, 4 bytes

l`.a

Try it online!

All test cases

\$\endgroup\$
2
\$\begingroup\$

JavaScript (ES6), 27 26 25 24 bytes

Takes input as a string.

s=>s.match(/\d/g).length
  • Saved two bytes thanks to Arnauld.
\$\endgroup\$
2
  • \$\begingroup\$ Your title says 23 bytes, but your code is 24... However, this is 23 bytes: s=>`${s>0?s:-s}`.length! \$\endgroup\$ Commented May 17, 2017 at 8:28
  • \$\begingroup\$ Thanks, @DomHastings. You should post yours as a separate answer as it's a different approach to mine. \$\endgroup\$
    – Shaggy
    Commented May 17, 2017 at 8:51
2
\$\begingroup\$

R, 18 bytes

nchar(abs(scan()))
\$\endgroup\$
2
\$\begingroup\$

JavaScript (ES6), 23 bytes

s=>`${s>0?s:-s}`.length

Different approach to Shaggy's answer.

\$\endgroup\$
1
  • 4
    \$\begingroup\$ s=>s.length-(s<0) saves 6 bytes \$\endgroup\$ Commented May 18, 2017 at 7:31
2
\$\begingroup\$

Bash, 15 bytes

wc -L<<<${1//-}

Try it online!

Deletes - from input as array, and otputs length of longest line (wc -c returns one char more than length)

\$\endgroup\$
2
\$\begingroup\$

Java, 30 24 bytes

i->(""+i.abs()).length()

Assumes i is a BigInteger. Also, the type is contextualized, so no imports are required, as shown in the test code.

Test

// No imports
class Pcg120897 {
  public static void main(String[] args) {
    java.util.function.ToIntFunction<java.math.BigInteger> f =
        // No full class declaration past here
        i->(""+i.abs()).length()
        // No full class declaration before here
      ;
    System.out.println(f.applyAsInt(new java.math.BigInteger("-1267650600228229401496703205376"))); // -(2^100)
    System.out.println(f.applyAsInt(new java.math.BigInteger("1267650600228229401496703205376"))); // (2^100)
  }
}

Saves

  • 30 -> 24 bytes : thanks to @cliffroot
\$\endgroup\$
2
  • \$\begingroup\$ +"" instead of .toString() ? \$\endgroup\$
    – cliffroot
    Commented May 18, 2017 at 11:26
  • 2
    \$\begingroup\$ +1 for providing sample code showing how this is invoked and for clarifying the type of i in your answer. I think more lambda answers should do this. \$\endgroup\$
    – Poke
    Commented May 18, 2017 at 13:32
2
\$\begingroup\$

Risky, 2 bytes

!?}*

Try it online!

! length
?     input
}   base convert
*     10
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.