How long is my number?

26

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.

Beta Decay

Posted 2017-05-16T19:31:57.583

Reputation: 21 478

Answers

10

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.

user62131

Posted 2017-05-16T19:31:57.583

Reputation:

This is where I stop scrolling... this is outrageous! – Bogdan Alexandru – 2017-05-18T13:46:19.640

39

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.

Engineer Toast

Posted 2017-05-16T19:31:57.583

Reputation: 5 769

8I've been a lurker in this exchange for a long time, but have never seen something like this – Cup of Java – 2017-05-17T00:35:30.600

@CupofJava https://codegolf.stackexchange.com/a/57064/65836

– Stephen – 2017-05-17T01:46:54.743

7Will this run out of gas if the number is long enough? – Robert Fraser – 2017-05-17T08:58:27.170

5This is a bigger brainfuck than brainfuck. – Omega – 2017-05-17T11:43:33.213

1@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 – 2017-05-17T12:21:16.550

@CupofJava Welcome to esoteric languages. Chicken, Cow, and Unary are some that I find the most hilarious. I presumed that would be more Taxi on PCG but it looks like just me and Erik the Outgolfer.

– Engineer Toast – 2017-05-17T12:28:29.470

1

@CupofJava OH MY GOSH how did I forget about Shakespeare.

– Engineer Toast – 2017-05-17T16:09:49.997

18

Mathematica, 13 bytes

IntegerLength

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

Martin Ender

Posted 2017-05-16T19:31:57.583

Reputation: 184 808

2Mathematica prevails :D – Beta Decay – 2017-05-16T20:03:05.597

1not in code golf it doesn't :) – Greg Martin – 2017-05-16T20:16:40.250

8There's a built-in: When isn't there? – TheLethalCoder – 2017-05-17T14:56:01.050

14

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

Digital Trauma

Posted 2017-05-16T19:31:57.583

Reputation: 64 644

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. – None – 2017-05-17T08:02:27.027

12

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.

Martin Ender

Posted 2017-05-16T19:31:57.583

Reputation: 184 808

5

05AB1E, 2 bytes

Äg

Try it online! or Try All Tests!

Ä  # Absolute value
 g # Length

Riley

Posted 2017-05-16T19:31:57.583

Reputation: 11 345

Ä, huh? Not þ? Fair enough. – Magic Octopus Urn – 2017-05-16T19:42:15.053

@carusocomputing I thought of Ä first, but þ would handle a decimal point, so it's a little better I guess. – Riley – 2017-05-16T19:43:51.667

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 – 2017-05-16T19:45:09.450

5

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.

Martin Ender

Posted 2017-05-16T19:31:57.583

Reputation: 184 808

4

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

Jörg Hülsermann

Posted 2017-05-16T19:31:57.583

Reputation: 13 026

1The first one doesn't work, for example, for 10, because ^ has lower priority. You can fix it with -~. – user63956 – 2017-05-17T05:36:02.427

Why not simply <?=strlen(abs($argn)); ? – roberto06 – 2017-05-17T08:38:03.123

@user63956 The version with log10 can't work in cases of input zero so I delete it. – Jörg Hülsermann – 2017-05-17T10:01:46.447

@roberto06 if i use abs for higher numbers the string will be interpreted as 1.0E+64 for example gives back 7 and not 64 – Jörg Hülsermann – 2017-05-17T10:04:09.030

1@JörgHülsermann Why not just $argn?:1? It would be 26 bytes with log10() and abs(). – user63956 – 2017-05-17T10:51:08.033

@user63956 I was a little confused through your first post. I am not sure if you forget to add 1 or cast to int. I count 28 Bytes – Jörg Hülsermann – 2017-05-17T11:15:59.390

1@JörgHülsermann -~$x is equivalent to ((int)$x)+1. <?=-~log10(abs($argn?:1)); seems to work. – user63956 – 2017-05-17T11:24:37.327

@user63956 Yes it works now I have understand what you mean. Thank You And we can remove the ternary operator cause log10(0) is interpreted as false – Jörg Hülsermann – 2017-05-17T11:47:52.620

4

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

waffleston

Posted 2017-05-16T19:31:57.583

Reputation: 71

1Welcome to PPCG! – Martin Ender – 2017-05-17T14:48:09.280

3

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.

colsw

Posted 2017-05-16T19:31:57.583

Reputation: 3 195

How about "$args".trim('-')|% Le* ? :) – whatever – 2017-05-17T09:20:08.300

3

05AB1E, 2 bytes

þg

Try it online!

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

Magic Octopus Urn

Posted 2017-05-16T19:31:57.583

Reputation: 19 422

3

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)

Value Ink

Posted 2017-05-16T19:31:57.583

Reputation: 10 608

1What magic is this? – Chowlett – 2017-05-17T15:51:45.377

2@Chowlett added an explanation. – Value Ink – 2017-05-17T19:39:03.243

3

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

Business Cat

Posted 2017-05-16T19:31:57.583

Reputation: 8 927

Is it possible to add a footer to the TIO link which outputs the result as a number? – Beta Decay – 2017-05-18T18:36:09.770

@BetaDecay Added – Business Cat – 2017-05-18T18:42:01.460

That's brilliant, thanks :D – Beta Decay – 2017-05-18T19:52:34.873

2

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

Jonathan Allan

Posted 2017-05-16T19:31:57.583

Reputation: 67 804

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 – 2017-05-16T19:43:07.193

1Not 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 – 2017-05-16T19:45:36.410

[-6.0, -5.0, -4.321000000000026], actually, apparently. – Magic Octopus Urn – 2017-05-16T19:46:36.473

Ah - yeah just edited - floating point arithmetic. – Jonathan Allan – 2017-05-16T19:47:43.013

2

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,

Business Cat

Posted 2017-05-16T19:31:57.583

Reputation: 8 927

Or also 5: rizs,. – Martin Ender – 2017-05-16T19:42:46.727

2

JavaScript (ES6), 27 26 25 24 bytes

Takes input as a string.

s=>s.match(/\d/g).length
  • Saved two bytes thanks to Arnauld.

Shaggy

Posted 2017-05-16T19:31:57.583

Reputation: 24 623

Your title says 23 bytes, but your code is 24... However, this is 23 bytes: s=>`${s>0?s:-s}`.length! – Dom Hastings – 2017-05-17T08:28:36.780

Thanks, @DomHastings. You should post yours as a separate answer as it's a different approach to mine. – Shaggy – 2017-05-17T08:51:17.843

2

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

Luke

Posted 2017-05-16T19:31:57.583

Reputation: 4 675

2

RProgN 2, 2 bytes

âL

Try it online!

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

ATaco

Posted 2017-05-16T19:31:57.583

Reputation: 7 898

2

JavaScript (ES6), 23 bytes

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

Different approach to Shaggy's answer.

Dom Hastings

Posted 2017-05-16T19:31:57.583

Reputation: 16 415

3s=>s.length-(s<0) saves 6 bytes – Johan Karlsson – 2017-05-18T07:31:18.750

2

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

Olivier Grégoire

Posted 2017-05-16T19:31:57.583

Reputation: 10 647

+"" instead of .toString() ? – cliffroot – 2017-05-18T11:26:14.997

2+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 – 2017-05-18T13:32:07.407

1

Python 2, 31 22 bytes

-9 bytes thanks to Rod.

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

Try it online!

totallyhuman

Posted 2017-05-16T19:31:57.583

Reputation: 15 378

1len(\abs(s)`)` with number as input is shorter – Rod – 2017-05-16T19:39:00.780

2Too bad Python doesn't have function composition. It would be just len∘repr∘abs. – Roberto Bonvallet – 2017-05-17T16:13:03.413

1

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.

James

Posted 2017-05-16T19:31:57.583

Reputation: 54 537

I count 62 bytes..? – totallyhuman – 2017-05-16T20:44:13.293

1@totallyhuman see my edit. – James – 2017-05-16T20:55:40.093

49 bytes: ([{}]((((()()()()())){}{})){}{})({(<()>)}{}[]<>) – Nitrodon – 2017-05-17T01:40:28.157

1

Ruby, 20 bytes

->a{a.abs.to_s.size}

marmeladze

Posted 2017-05-16T19:31:57.583

Reputation: 227

FYI: in order to call it you do: ->a{a.abs.to_s.size}[-95] – Filip Bartuzi – 2017-05-18T09:36:25.217

or just classic way - ->a{a.abs.to_s.size}.call(-92) – marmeladze – 2017-05-18T09:38:36.430

2not a golfy way :D – Filip Bartuzi – 2017-05-18T09:39:43.733

1

C++, 80 76 bytes

#include<string>
int main(int,char**c){printf("%d",strlen(c[1])-(*c[1]<46));}

Prints the length of the argument, minuses 1 if the first character is a minus because bool guarantees conversion to 1 if true or 0 if false

  • 4 bytes thanks to @Squidy for pointing out I can use <46 instead of =='-', and to deference the array instead of []

Tas

Posted 2017-05-16T19:31:57.583

Reputation: 593

You could shave off 4 bytes by replacing c[1][0]=='-' with *c[1]<46 since we can assume the input will always be a valid integer. (Unless prefixes other than '-' are allowed...) – Squidy – 2017-05-17T23:39:35.957

@Squidy oh wow nice find! I racked my brain for ages trying to shorten this and never even came up with that! Thanks for the suggestion, and especially for signing up to PCCG to let me know! – Tas – 2017-05-17T23:50:31.250

1

Pyth, 4 bytes

l`.a

Try it online!

All test cases

clap

Posted 2017-05-16T19:31:57.583

Reputation: 834

1

R, 18 bytes

nchar(abs(scan()))

Sven Hohenstein

Posted 2017-05-16T19:31:57.583

Reputation: 2 464

1

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

Leo

Posted 2017-05-16T19:31:57.583

Reputation: 8 482

1

GNU Make, 78 bytes

Imperative style:

$(eval T=$1)$(foreach D,$(shell seq 9),$(eval T=$(subst $D,? ,$T)))$(words $T)

Functional style, 113 bytes:

$(eval 2?=$(shell seq 9))$(if $2,$(call $0,$(subst $(word 1,$2),? ,$1),$(wordlist 2,$(words $2),$2)),$(words $1))

Pure Make, 83 bytes:

$(eval T=$1)$(foreach D,0 1 2 3 4 5 6 7 8 9,$(eval T=$(subst $D,? ,$T)))$(words $T)

eush77

Posted 2017-05-16T19:31:57.583

Reputation: 1 280

1

TI-Basic (TI-84 Plus CE, OS 5.2+), 6 bytes

length(toString(abs(Ans

TI-Basic is a tokenized language; length( and toString( are two bytes each.

Ans is used as implicit input; the last (only) line's value is implicitly returned.

Pretty simple, takes the absolute value to get rid of a minus sign, converts to string, returns the length of the string.

A 6-byte mathematical approach that doesn't work for 0:

1+log(abs(Ans

pizzapants184

Posted 2017-05-16T19:31:57.583

Reputation: 3 174

Which calculators have toString(? – kamoroso94 – 2017-05-19T05:20:14.300

@kamoroso94 TI-84 Plus CE – pizzapants184 – 2017-05-19T16:16:44.653

1

Pari/GP, 13 bytes

n->#digits(n)

Try it online!

alephalpha

Posted 2017-05-16T19:31:57.583

Reputation: 23 988

1

Excel VBA, 15 Bytes

Anonymous VBE immediate window function that takes input from [A1] and outputs to the VBE immediate window

?[Len(Abs(A1))]

Taylor Scott

Posted 2017-05-16T19:31:57.583

Reputation: 6 709

0

Fourier, 30 bytes

I~S<0{1}{-2*S~S}S{0}{S^~S}SL^o

Try it on FourIDE!

Fourier doesn't have strings, so it uses logs instead. Bytes are wasted on supporting zero and negative numbers.

Beta Decay

Posted 2017-05-16T19:31:57.583

Reputation: 21 478

0

MATL, 6 bytes

nGU0<-

Try it online!

Explanation

n     % Implicitly input a string. Push its length
G     % Push input again
U     % Convert to number (floating-point double). Although integers with absolute
      % value exceeding 2^53 cannot be represented exactly, the sign is correct
0<    % Is it negative?
-     % Subtract. Implicitly display

Luis Mendo

Posted 2017-05-16T19:31:57.583

Reputation: 87 464

0

Befunge, 35 bytes

77*~`!1+:v
~0`#@    ># !#. #- #2_1+

Try it online!

77*~`!            add 49 to the stack and see if that is less than 50 (ascii for
                  '-') 
1+:v              if there is a -, don't count it. Add 1 so we don't
                  have a zero at the top of the stack. Move down.
># !#. #- #2_1+   move right and add one to the total. (Will remove later)
~0`#@             Loop back around and take an input and make sure it is not end of 
                  the string (-1, so we make sure it is > 0)
># !#. #- #2_1+   check to see if there was an input. If there was, add one to the 
                  total. If not, move left. Subtract 2 because we added 1 at two 
                  different locations. Print output and end program.

bwillsh

Posted 2017-05-16T19:31:57.583

Reputation: 11

0

Bean, 20 bytes

Hexdump:

00000000: 2650 80d3 d080 a05d 2080 0921 8181 0020  &P.ÓÐ. ] ..!... 
00000010: 8001 dc64                                ..Üd

JavaScript equivalent:

a.match(/\d/g).length;

Explanation:

Implicitly takes input as a decimal string in a and implicitly outputs the length of the match, which is all the decimal digits in the string. Returns 1 for input of 0.

See Demo.

Bean, 22 bytes

Hexdump:

00000000: 2aa0 1f26 4ccc d3a0 8043 53a0 802d 2043  * .&LÌÓ .CS .- C
00000010: 9125 398b 253a                           .%9.%:

JavaScript equivalent:

with(Math)((log10(abs(A))^0)+1);

Explanation:

Implicitly takes input as a decimal integer in A, takes the absolute value, then log-base-10, XORs with 0, then adds 1.

When A is 0, the returned value of log10() is -Infinity, and -Infinity ^ 0 is 0 in JavaScript, so the returned value for 0 is 1.

See Demo.

Patrick Roberts

Posted 2017-05-16T19:31:57.583

Reputation: 2 475

0

J, 7 bytes

#@":@**

Try it online!

All the solutions I came up with:

0>.@>.10^.>:@(**)
[:#10&#.inv
#@-.&'-'
#@":@**

The first one is math, the second is base conversion, the third takes a string as input, and the shortest takes a number.

The current solution looks like this:

              ┌─ # 
        ┌─ @ ─┴─ ":
  ┌─ @ ─┴─ *       
──┴─ *             

The parent root is a hook between the upper tine and the lower tine. The lower tine (*) is a monad that calculates magnitude. The upper tine is a composition:

         ┌─ # 
   ┌─ @ ─┴─ ":
@ ─┴─ * 

This composes the upper tine (another composition) with *, in this case, a dyad. This is the dyad for multiplication. In the last tine:

   ┌─ # 
@ ─┴─ ":

This calculates format (":) then length (#).

In English form, this is "multiply x times the sign of x, then convert this to a string, then take the length of this string". Basically, abs.toString.length.

Conor O'Brien

Posted 2017-05-16T19:31:57.583

Reputation: 36 228

0

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.

user62131

Posted 2017-05-16T19:31:57.583

Reputation:

0

C#, 33 bytes

i=>Math.Abs(i).ToString().Length;

Bojan B

Posted 2017-05-16T19:31:57.583

Reputation: 101

You need to fully qualify Math and you can save bytes by using +"" instead of ToString(). – TheLethalCoder – 2017-05-17T14:51:14.247

0

MATL, 4 bytes

47>s

Inspired by Martin's Retina answer: count how many characters have code point exceeding 47 (this excludes the minus sign).

Try it online!

Luis Mendo

Posted 2017-05-16T19:31:57.583

Reputation: 87 464

0

Braingolf, 2 bytes

dl

Explaination:

dl
    Implicit input from command-line args to stack
d   Pop last item from stack, split it into digits, and push each digit to the stack
 l  Push length of stack to the end of the stack
    Implicit output of last item on stack

Skidsdev

Posted 2017-05-16T19:31:57.583

Reputation: 9 656

0

Brain-Flak, 48 + 3 ( -a) = 51 bytes

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

Try it online!

Erik the Outgolfer

Posted 2017-05-16T19:31:57.583

Reputation: 38 134

0

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

theblitz

Posted 2017-05-16T19:31:57.583

Reputation: 1 201

0

C#, 28 bytes

s=>s.Replace("-","").Length;

TheLethalCoder

Posted 2017-05-16T19:31:57.583

Reputation: 6 930

0

C#, 24 bytes

n=>$"{n>0?n:-n}".Length;

Inspired from @DomHastings answer.

TheLethalCoder

Posted 2017-05-16T19:31:57.583

Reputation: 6 930

0

Chaincode, 5 bytes

pqL_+

Explanation

pqL_+ print(
    +   succ(
   _      floor(
  L        log_10(
pq           abs(
               input())))))

Roman Gräf

Posted 2017-05-16T19:31:57.583

Reputation: 2 915

0

C, 43 bytes

f(char*s){printf("%d",strlen(s)-(*s==45));}

Try it online

Johan du Toit

Posted 2017-05-16T19:31:57.583

Reputation: 1 524

0

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)

marcosm

Posted 2017-05-16T19:31:57.583

Reputation: 986

0

T-SQL, 38 bytes

CREATE PROC l @ BIGINT AS PRINT LEN(@)

Usage:

EXECUTE l @ = 9999999999

WORNG ALL

Posted 2017-05-16T19:31:57.583

Reputation: 61

If it's a negative int, it returns an extra number in the result. Probably need to add LEN(ABS(@)) – phroureo – 2017-10-02T22:16:43.277

0

Lua, 26 bytes

Replaces all occurrences of '-' with the empty string '' and get length with #.

print(#(...):gsub('-',''))

Try it online!

Felipe Nardi Batista

Posted 2017-05-16T19:31:57.583

Reputation: 2 345

0

Perl 5, 9 bytes + 3 for -F flag=12 bytes

say@F-/-/

Run like perl -F -E 'say@F-/-/'. Takes a single number from stdin without a trailing newline. Can add the -l flag at the cost of an extra byte if you would rather have it accept a trailing newline.

The -F flag auto splits stdin into the array @F. In scalar context, @F evaluates to the length of the array, which is the number of characters in $_ (which comes from stdin). /-/ in a numerical context evaluates to 1 if $_ has a minus sign in it or 0 if $_ does not have a minus sign in it, so @F-/-/ evaluates to the number of non-minus sign characters (i.e. the number of digit characters) read from stdin.

Chris

Posted 2017-05-16T19:31:57.583

Reputation: 1 313

0

C, 71 38 bytes

  • -33 bytes FelipeNardiBatista

Try Online

f(char*t){return*t?(*t>'-')+f(t+1):0;}

Khaled.K

Posted 2017-05-16T19:31:57.583

Reputation: 1 435

why don't you just return the number? – Felipe Nardi Batista – 2017-05-18T10:57:03.297

golfed to 38 bytes – Felipe Nardi Batista – 2017-05-18T11:05:44.133

@FelipeNardiBatista changed now, thx – Khaled.K – 2017-05-18T11:19:42.463

0

Swift, 138 bytes

You would think there would be an easier way to do this.

import Foundation;var d:(String)->Int={return $0.trimmingCharacters(in:CharacterSet(charactersIn:"0123456789").inverted).characters.count}

You can try it here

Un-golfed:

import Foundation // Import the Foundation module

var d:(String)->Int={ // Create a closure that takes in a String and returns an Int

    return // Return the following

    $0.trimmingCharacters(in:  // Removes all characters in the following CharacterSet

        CharacterSet(charactersIn:"0123456789").inverted // Create a CharacterSet with all characters that are not digits

    ).characters.count // Get the length of the resulting String
}

Caleb Kleveter

Posted 2017-05-16T19:31:57.583

Reputation: 647

0

Axiom, 23 Bytes

f(x)==#(abs(x)::String)

RosLuP

Posted 2017-05-16T19:31:57.583

Reputation: 3 036

0

awk, 22 bytes

$1=length($1<0?-$1:$1)

Try it online!

All test cases

steve

Posted 2017-05-16T19:31:57.583

Reputation: 2 276

1

You can save one byte by using sqrt($1^2) to take the absolute value. TIO.

– Chris – 2018-05-03T02:52:56.280

0

JavaScript, 23 bytes

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

Paul

Posted 2017-05-16T19:31:57.583

Reputation: 256

0

Jelly, 5 bytes

A‘l⁵Ċ

Try it online!

Christopher

Posted 2017-05-16T19:31:57.583

Reputation: 3 428