# How long is my number?

## 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.

# 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.

• This is where I stop scrolling... this is outrageous! – Bogdan Alexandru May 18 '17 at 13:46

# 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.
Keep picking up characters and adding 1 until you're out.
Convert the running total to a string and print to stdout.
• I've been a lurker in this exchange for a long time, but have never seen something like this – Cup of Java May 17 '17 at 0:35
• Will this run out of gas if the number is long enough? – Robert Fraser May 17 '17 at 8:58
• This is a bigger brainfuck than brainfuck. – Omega May 17 '17 at 11:43
• @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. – Engineer Toast May 17 '17 at 12:21
• @CupofJava OH MY GOSH how did I forget about Shakespeare. – Engineer Toast May 17 '17 at 16:09

## Mathematica, 13 bytes

IntegerLength

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

• Mathematica prevails :D – Beta Decay May 16 '17 at 20:03
• not in code golf it doesn't :) – Greg Martin May 16 '17 at 20:16
• There's a built-in: When isn't there? – TheLethalCoder May 17 '17 at 14:56

# 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.

?    # input
Z   # measure length
p  # print
• 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. – user62131 May 17 '17 at 8:02

## 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.

# 05AB1E, 2 bytes

Äg
Ä  # Absolute value
g # Length
• Ä, huh? Not þ? Fair enough. – Magic Octopus Urn May 16 '17 at 19:42
• @carusocomputing I thought of Ä first, but þ would handle a decimal point, so it's a little better I guess. – Riley May 16 '17 at 19:43
• 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. – Magic Octopus Urn May 16 '17 at 19:45

## 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".
!      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 " ".
/      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.

# 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
• Is it possible to add a footer to the TIO link which outputs the result as a number? – Beta Decay May 18 '17 at 18:36
• That's brilliant, thanks :D – Beta Decay May 18 '17 at 19:52

<?=-~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!

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

# Fortran 95 (gfortran), 12196 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

• Welcome to PPCG! – Martin Ender May 17 '17 at 14:48

$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!

• Welcome to Code Golf, nice first answer! – Redwolf Programs Dec 20 '20 at 21:30
• You could use gsub(".",1) to knock off a few more characters too. Nice idea for how to do this BTW. – cnamejj Dec 20 '20 at 21:35
• Thanks, guys! @cnamejj I could not make this work with negative numbers. – Pedro Maimere Dec 20 '20 at 21:41
• @cnamejj you have just gave me an idea to regex every character, but the minus sign. I'll save one byte. – Pedro Maimere Dec 20 '20 at 22:00
• 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. – manatwork Dec 20 '20 at 22:21

# 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. • How about "$args".trim('-')|% Le* ? :) – whatever May 17 '17 at 9:20

# 05AB1E, 2 bytes

þg

Try it online!

# Implicit input [a]...
þ  # Only the digits in [a]...
g # length of [a]...
# Implicit output.

# 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)
• What magic is this? – Chowlett May 17 '17 at 15:51
• @Chowlett added an explanation. – Value Ink May 17 '17 at 19:39

# 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
• 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. – Magic Octopus Urn May 16 '17 at 19:43
• 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]) – Jonathan Allan May 16 '17 at 19:45
• [-6.0, -5.0, -4.321000000000026], actually, apparently. – Magic Octopus Urn May 16 '17 at 19:46
• Ah - yeah just edited - floating point arithmetic. – Jonathan Allan May 16 '17 at 19:47

# Python 2, 31 22 bytes

-9 bytes thanks to Rod.

lambda i:len(abs(i))

Try it online!

• len(abs(s)) with number as input is shorter – Rod May 16 '17 at 19:39
• Too bad Python doesn't have function composition. It would be just len∘repr∘abs. – Roberto Bonvallet May 17 '17 at 16:13

# 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,
• Or also 5: rizs,. – Martin Ender May 16 '17 at 19:42

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

# RProgN 2, 2 bytes

âL

Try it online!

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

# JavaScript (ES6), 272625 24 bytes

Takes input as a string.

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

• s=>s.length-(s<0) saves 6 bytes – Johan Karlsson May 18 '17 at 7:31

# 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
• +"" instead of .toString() ? – cliffroot May 18 '17 at 11:26
• +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. – Poke May 18 '17 at 13:32

# 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.

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

# 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.

• I count 62 bytes..? – totallyhuman May 16 '17 at 20:44
• @totallyhuman see my edit. – James May 16 '17 at 20:55
• 49 bytes: ([{}]((((()()()()())){}{})){}{})({(<()>)}{}[]<>) – Nitrodon May 17 '17 at 1:40

# Ruby, 20 bytes

->a{a.abs.to_s.size}
• FYI: in order to call it you do: ->a{a.abs.to_s.size}[-95] – Filip Bartuzi May 18 '17 at 9:36
• or just classic way - ->a{a.abs.to_s.size}.call(-92) – marmeladze May 18 '17 at 9:38
• not a golfy way :D – Filip Bartuzi May 18 '17 at 9:39

l`.a

Try it online!

All test cases

# 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.

## R, 18 bytes

nchar(abs(scan()))

# Alice, 10 bytes (non-competing)

/d/
O@IHc

Try it online!

This is a non-competing solution, because at the time this challenge was posted the command c was bugged in the official (and only :D) interpreter. Martin Ender fixed it in the meanwhile, so this now works.

### Explanation

The instruction pointer passes through the two mirrors (/) multiple times, so it may be a bit difficult to follow. I'll try to explain it as clearly as I can, using cardinal directions (e.g. N is up, SW is down to the left...). I'll call /1 the leftmost mirror, and /2 the rightmost one.

Command    Direction    Comment
E        Execution starts from the upper-left corner going right
/1        E → SE     Passing through the mirror changes direction and switches
to ordinal mode (string operations)
I        SE → NE     Push the input string to the stack, then bounce against
the bottom of the code
/2       NE → S      Back to cardinal mode (numeric operations)
H           S        Pop n, push abs(n). Execution wraps from bottom to top
/2        S → SE     Ordinal mode again
c        SE → NW     Pop s, push each char of s separatedly. Bounce against
the bottom right corner
/2       NW → W      Cardinal mode
d           W        Push the depth of the stack (which is now equal to
the number of characters in abs(input))
/1     W → NW → SW   Pass through the mirror, then bounce agains the top
O        SW → NE     Output the result, then bounce on the bottom left corner
/1       NE → S      Last mirror, I promise
@           S        Terminate execution

# REXX 22 Bytes

arg "-" a
say length(a)

Explanation: There is no distinction in Rexx between numbers and strings. The action you perform is what defines the type. The "typing" applies just to that action and can change at any time.

So, here the number (say -20) is treated as a string. The "arg" instruction (short for parse arg) tells Rexx to search for the first "-" and then put everything after it in the variable "a". If "-" is not found then everything goes in "a".

Try it here

REXX functions and instructions