# Finding number of digits in an integer [closed]

Given an integer n as input write a program to output the numbers of digit in it.

Input

12346

456


Output

5

3


Constraint

n<=10^9

• This seems overly trivial... – Doorknob Jan 26 '14 at 15:35
• I agree with @DoorknobofSnow. It should be trivial. But many or most of the submitted answers are incorrect. Any solution based on string.length alone (currently most, below) will output the wrong number of digits for any negative integer. And most values of n will be negative, since "n<=10^9". Just sayin'. ;-) – Darren Stone Jan 27 '14 at 5:40
• Is the Input/Output example supposed to represent two separate inputs & outputs, or is the program supposed to be able to handle multiple integers at once? Also, are we required to support negative integers and if so what is the lower bound? – Iszi Jan 28 '14 at 16:18
• Should 00501 return 3 or 5? – user15259 Jan 28 '14 at 19:32
• @Dangling_pointer did you mean that |n|<=10⁹? – Tyzoid Jan 28 '14 at 21:58

# GolfScript, 1 character

,


, means length...

Edit: You seem to have changed your question... please don't do that, but I still have a solution:

# GolfScript, 12 7 characters (for multiline)

n%{,n}/


Thanks @Howard for reminding me about n to push newline and using separate strings instead of one, to save 5 chars ;)

Solutions that work with negative numbers:

# GolfScript, 5 (for negative)

'-'-,


# GolfScript, 11 (for multiline and negative)

n%{'-'-,n}/

• Only if input has no newline with it. – Howard Jan 26 '14 at 15:37
• n%{,}%n* is much shorter ;-) – Howard Jan 26 '14 at 15:57
• @Howard Thanks, forgot about n :) – Doorknob Jan 26 '14 at 15:57
• Or even n%{,n}/. – Howard Jan 26 '14 at 15:59
• @Howard Oh wow, thanks! Took a bit for me to figure out how that works. – Doorknob Jan 26 '14 at 16:00

# Perl

s/\D//;$_=length  run as: perl -ple 's/\D//;$_=length'

• works correctly for negative, and "Perl style" numbers like 1_000_000 – glezmen Jan 28 '14 at 15:22
• Nice use of s///, but I think you need a g at the end for numbers like 1_000_000_000? Also, how about $_=s/\d//g? :) – Dom Hastings Jan 28 '14 at 18:05 • Unfortunately this returns the length of all input whether its an integer or not :( For eg. AAA returns 0 & a1a2 would return 2. – draegtun Jan 28 '14 at 18:34 • @draegtun This is codegolf; The question says nothing about invalid input, so you ignore it ("Given an integer n ..."). – daniero Jan 28 '14 at 18:44 • If you care about input validation, perl -ple"$_=y/0-9//" seems like the proper way to do it. – primo Jan 29 '14 at 16:31

I'm trying to stay away from the simple string length functions, but the BF solution basically does a count.

# Pure math/Mathematica - 22 chars (for mathematica)

floor(log10(abs(n)))+1


Thanks to @plg for the correction when n is a power of 10. This invokes undefined behavior when n=0, but that case can be returned by a simple check.

# PHP implementation of the above math solution - 34 chars

($n==0)?1:floor(log(abs($n),10))+1;


# BrainF*ck - 54 characters

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

• How about using log10() : ceil(log10(abs(n)) EDIT: this won't work for powers of 10! – ThinkChaos Jan 28 '14 at 20:02
• This took me longer than it should have, but here's a working pure math solution : floor(log10(abs(n))) + 1 – ThinkChaos Jan 28 '14 at 20:41
• @plg I'm just realizing that both of our solutions fail when x=0 – Tyzoid Jan 28 '14 at 21:50

# Dc: 3 characters

?Zp


Sample run:

bash-4.2$dc -e '?Zp' <<< '12346' 5 bash-4.2$ dc -e '?Zp' <<< '345'
3

• I like how this (unintentionally?) works for negative numbers if you use something like -123 as input. – daniero Jan 28 '14 at 18:38

## python 2, 25

print len(abs(input()))


works for both positive and negative integers

# PHP (30 chars)

echo $n<0?(strlen($n)-1):strlen($n) (without php opening tags <?php & ?>) ## Explanation Pretty simple, ints can be interpreted as strings, therefore $n<0 has a minus-char that should be removed in the true-statement of the ternary operator. If its positive then we just count the length ;)

• You need to count the tags, but you don't have to close them, and there is a shorter version (I think it was <?) so just prepend that to your code and you'll be good. – Justin Jan 30 '14 at 0:45

# Java 8, 29 28 bytes

i->(""+(i<0?-i:i)).length();


# Ungolfed test program

public static void main(String[] args) {
IntFunction<Integer> func = i -> ("" + (i < 0 ? -i : i)).length();

System.out.println(func.apply(12345)); //5
}


# Perl (with -lp) (11 bytes, counting lp)

$_=length  ## Befunge-98, 8 or 12 chars Single number (actually counts input bytes ≥15 and prints count at EOF) #.~f+#@  Multiline support (same as above, but print count at byte <15 and reset counter) #@~f:2*j\.+  • I thought ~$1+2j@. makes more sense for single number. – Justin Jan 27 '14 at 0:48
• I suppose so, but I wanted to support a trailing newline even for the single-number one, since it doesn't cost me anything. As for the more straightforward 2j, I usually forget about that, but you're right that it's prettier that way. – FireFly Jan 27 '14 at 8:20

# C - 59 characters

main(k){scanf("%i",&k);printf("%i\n",(int)log10(abs(k))+1);}

• You can save a character by changing your variable declaration to be inside the function declaration: main(k) – Josh Jan 28 '14 at 14:55

A DELPHI PROGRAM FOR CONSOLE

program P;
{$APPTYPE CONSOLE} uses System.SysUtils; var a: Integer; begin readln(a); writeln(length(IntToStr(a))); end.  Ruby $*.first.size


or

ARGV.first.size

• Welcome, shemerey. Remember... code-golf... keep it short. Why not simply $*.size? (Aside from the negative integers issue.) – Darren Stone Jan 29 '14 at 4:21 ## Go, 67 bytes package main;import."fmt";func main(){s:="";Scan(&s);Print(len(s))}  • len(strconv.Itoa(i)) – dmytrivv Mar 8 at 21:45 ## R, 25 bytes cat(nchar(scan("stdin")))  # Python 2, 22 bytes lambda a:len(abs(a))  I actually built this myself, before seeing Wasi's answer! This is how I thought of it: • I need: a lambda. • len? False! What about n<0? Should the - be counted? False! • How to eliminate the - in just a few bytes? abs! [Thinking ends] • Seems this is one of only a few of the answers which actually account for negative integers. There go 5 bytes. – Erik the Outgolfer Sep 6 '16 at 10:14 # k [7 chars] f:{#$x}


Example:

f 12346
5

f 456
3


Though only 2 characters (#$) are required to find the length of the input number. #$123444
6


# Explanation

convert the input to string.

$123456 "123456"  count the number of characters: #$123456
6


Q equivalent of this code:

f:{count string x}
f 123456
6


# JavaScript, 20

alert((""+n).length)

• “SyntaxError: return not in function” – Why you changed the alert()? – manatwork Jan 26 '14 at 16:37
• @manatwork Ok I will change it. I thought it was shorter with return but forgot that return has one more character than alert. – Blue Sheep Jan 26 '14 at 16:41

### R

The solution at 18 characters (identical in concept to the python solution of Wasi):

nchar(abs(scan()))


And the funnier one at 33 characters:

which(!abs(scan())%/%10^(1:9))


## GTB, 3

l?_


To make user input:

_l?_


Newline support with interactive input:

[_~l?_]


# bash - 19 characters

Assuming input via standard input:

grep -o [0-9]|wc -l


Multi-line version - 48 characters:

while read L;do echo $L|grep -o [0-9]|wc -l;done  ### Perl ### 15 chars - no input or constraint checks $_=()=$_=~/\d/g  ### 48 chars - checks input & constraint $_=/^-?(\d+)$/?($1<=10**9?length($1)."\n":$_):$_  NB. If the input ($_) is an integer (positive or negative) and comes under the constraint then it amends $_ to the number of digits. Otherwise it just leaves the input as is. Usage example: perl -ple '... insert above code...'  ### APL - 4 characters ρ'n'  The first symbol, rho, checks the number of cells in an array, where one character of a string is equal to one cell. ## C, 6359 57 characters It's slightly longer than the other C solution, but it works on arbitrarily large numbers (numbers with 2^32 - 1 digits rather than numbers up to 2^32 - 1). EDIT: It's now shorter than the other C solution! c;main(n){n-10?main(getchar(),c+=n>47):printf("%d\n",c);}  Note: if you call the program with exactly 9 arguments, it will fail. But why would you do that?? ## PowerShell (25) ($n-replace"-",'').length


where $n is a number • Incorrect for negative numbers – Adam Speight Jan 30 '14 at 2:48 • @AdamSpeight Arguably, the challenge is unclear (and the OP has yet to edit it in response to this and other points) with regards to negative numbers. However, adding negative number support would bring it to 39: $x="$n".length;if($n-ge0){$x}else{$x-1} – Iszi Jan 30 '14 at 2:54
• I have modified my answer, i think it should work for negative numbers. The question is very unclear, it is unbounded on negative side. – microbian Jan 30 '14 at 6:17
• @microbian Kill two more characters - the spaces are unnecessary. – Iszi Jan 30 '14 at 6:35
• Scratch another character - substitute '-' instead of "\D". – Iszi Jan 31 '14 at 4:10

# Tcl, 26 bytes

puts [string length \$argv]


Try it online!

# 05AB1E, 2 bytes

þg


Explanation:

þ     # Take the digits of the input
g    # And output the length


# Japt, 2 bytes

ìl


Try it

ì converts to a digit array and l gets the length.

# RProgN 2, 2 bytes

âL


Gets the length of the Absolute Value of the input. Trivial.

Try it online!

# Braingolf, 5 bytes

!s*dl


Try it online!

As with all the others, abs then len

# Thing, 12 bytes

idh\-=[tLe]L


Try it online!

## How?

Gets input from command line arguments. If the first character of input is "-", push the length of the all but first items of the string and immediately end the program. Else, push the length of the string. Then implicitly print.

Does not work with multiline.

i push input
d duplicate
h first character of
\- push the character "-"
= if top two values are equal, push 1, if not, 0
[ if top value is truthy (not [] or 0), go into the block. if not,  go past the end of the block.
t push the all but first items of the stack's top value (literally s[1:] in python)
L length
e end the program
] end loop
L length