How much do I have to write?

35

2

Writing out numbers is among the Hello worlds of programming, often the numbers 1-10.

I want to write out many numbers! Many, Many numbers. But how many numbers do I have to write?

Task

Given an integer input, give a number as output that would give me the number of digits that would be in a string containing all integer numbers in the range from 0 to the input, inclusive. The negation identifier ("-") counts as a single character.

Example I/Os

Input: 8
Written out: 0,1,2,3,4,5,6,7,8
Output: 9

Input: 101
written out: 0,1,2,3....,99,100,101
Output: 196

Input: 102
written out: 0,1,2,3....,100,101,102
output: 199

Input -10
Written out: 0,-1,-2,-3,-4,-5,-6,-7,-8,-9,-10
output: 22

This is a . The lowest number of bytes wins!

tuskiomi

Posted 2017-03-10T05:15:03.510

Reputation: 3 113

Answers

23

05AB1E, 3 bytes

Code:

ÝJg

Uses the CP-1252 encoding. Try it online!

Explanation:

Ý     # Range [0 .. input]
 J    # Join into one string
  g   # Get the length of the string

Adnan

Posted 2017-03-10T05:15:03.510

Reputation: 41 965

13

Python 2, 55 46 bytes

lambda n:len(`range(abs(n)+1)`)+2*~n+3*n*(n<0)

Try it online!

Getting better.

Jonathan Allan

Posted 2017-03-10T05:15:03.510

Reputation: 67 804

11

Röda, 23 bytes

f x{[#([seq(0,x)]&"")]}

Try it online!

Explained:

f x{[#([seq(0,x)]&"")]}
f x{                  } /* Defines function f with parameter x. */
        seq(0,x)        /* Creates a stream of numbers from 0 to x. */
       [        ]       /* Creates an array. */
                 &""    /* Joins with "". */
     #(             )   /* Calculates the length of the resulting string. */
    [                ]  /* Returns the value. */

fergusq

Posted 2017-03-10T05:15:03.510

Reputation: 4 867

10

Python 2, 41 bytes

f=lambda n:len(`n`)+(n and f(n+cmp(0,n)))

Try it online!

Dennis

Posted 2017-03-10T05:15:03.510

Reputation: 196 637

+1: You really cannot beat this intelligently made recursive solution with Python – micsthepick – 2017-03-16T22:28:50.993

7

Bash + OS X (BSD) utilities, 24 22 bytes

Thanks to @seshoumara for saving 2 bytes.

seq 0 $1|fold -1|wc -l

Test runs on Mac OS X:

$ for n in 8 101 102 -10 -1 0 1; do printf %6d $n; ./digitcount $n; done
     8       9
   101     196
   102     199
   -10      22
    -1       3
     0       1
     1       2

Here's a GNU version:

Bash + coreutils, 40 38 bytes

Again, 2 bytes saved thanks to @seshoumara.

(seq $1 0;seq 0 $1)|uniq|fold -1|wc -l

Try it online!

Mitchell Spector

Posted 2017-03-10T05:15:03.510

Reputation: 3 392

@tuskiomi I wrote coreutils when I meant BSD utilities -- I tested it in Mac OS X, where it does work on negative inputs too (seq there isn't the same as GNU seq). – Mitchell Spector – 2017-03-10T05:53:38.070

@DigitalTrauma Nice GNU solution. Go ahead and post it yourself if you'd like to; I think it's too different to count as a variant of mine. – Mitchell Spector – 2017-03-10T19:42:09.120

Ok, here you are :)

– Digital Trauma – 2017-03-10T19:58:54.300

How about using fold -1|wc -l to do the counting? It is shorter. – seshoumara – 2017-03-11T08:11:37.513

6

Python 2, 83 ,78 64 bytes

shortest version:

lambda x:sum(map(len,map(str,(range(0,x+cmp(x,.5),cmp(x,.5))))))

this version saved 5 bytes, thanks to @numbermaniac :

x=input()
print len(''.join(map(str,(range(x+1)if x>0 else range(0,x-1,-1)))))

Try it online!

this one I came up with on my own after that (same amount of bytes):

x=input()
print sum(map(len,map(str,(range(x+1)if x>0 else range(0,x-1,-1)))))

Try it online!

micsthepick

Posted 2017-03-10T05:15:03.510

Reputation: 421

You can use map on the second line for 78 bytes: print len(''.join(map(str,(range(x+1)if x>0 else range(0,x-1,-1))))). You might save even more by making it a lambda. – numbermaniac – 2017-03-10T06:07:37.393

1@numbermaniac can I do something similar this way? – micsthepick – 2017-03-10T06:12:45.157

1@numbermaniac here is an equivalent: print sum(map(len,map(str,(range(x+1)if x>0 else range(0,x-1,-1))))) – micsthepick – 2017-03-10T06:14:51.143

lambda x:sum(map(len,map(str,(range(x+1)if x>0 else range(0,x-1,-1))))) for 71 bytes – Felipe Nardi Batista – 2017-03-16T13:40:51.950

6

Java 7, 74 bytes (recursive - including second default parameter)

int c(int r,int n){r+=(n+"").length();return n>0?c(r,n-1):n<0?c(r,n+1):r;}

Explanation (1):

int c(int r, int n){     // Recursive method with two integer parameters and integer return-type
                         // Parameter `r` is the previous result of this recursive method (starting at 0)
  r += (n+"").length();  //  Append the result with the current number's width
  return n > 0 ?         //  If the input is positive
     c(r, n-1)           //   Continue recursive method with n-1
    : n < 0 ?            //  Else if the input is negative
     c(r, n+1)           //   Continue recursive method with n+1
    ?                    //  Else (input is zero)
     r;                  //   Return the result
}                        // End of method

Java 7, 81 79 bytes (loop - single parameter)

If having a default second parameter as 0 for this recursive approach isn't allowed for some reason, a for-loop like this could be used instead:

int d(int n){String r="x";for(int i=n;i!=0;i+=n<0?1:-1)r+=i;return r.length();}

Explanation (2)

int d(int n){                 // Method with integer parameter and integer return-type
  String r = "x";             //  Initial String (with length 1 so we won't have to +1 in the end)
  for(int i=n; i != 0;        //  Loop as long as the current number isn't 0
      i += n < 0 ? 1 : 1)     //   After every iteration of the loop: go to next number
    r += i;                   //   Append String with current number
                              //  End of loop (implicit / single-line body)
  return r.length();          //  Return the length of the String
}                             // End of method

Test code:

Try it here.

class M{
  static int c(int r,int n){r+=(n+"").length();return n>0?c(r,n-1):n<0?c(r,n+1):r;}

  static int d(int n){String r="x";for(int i=n;i!=0;i+=n<0?1:-1)r+=i;return r.length();}

  public static void main(String[] a){
    System.out.println(c(0, 8) + "\t" + d(8));
    System.out.println(c(0, 101) + "\t" + d(101));
    System.out.println(c(0, 102) + "\t" + d(102));
    System.out.println(c(0, -10) + "\t" + d(-10));
  }
}

Output:

9   9
196 196
199 199
22  22

Kevin Cruijssen

Posted 2017-03-10T05:15:03.510

Reputation: 67 575

1I like this solution, :) – tuskiomi – 2017-06-15T19:48:42.647

4

Ruby, 20 26 29 bytes

->x{[*x..-1,0,*1..x]*''=~/$/}

Try it online!

G B

Posted 2017-03-10T05:15:03.510

Reputation: 11 099

Why the increase? – Brian Minton – 2017-03-10T19:13:26.777

The first version did not work for negative numbers, the second version had a problem with zero as input. – G B – 2017-03-10T21:43:51.623

4

RProgN 2, 5 bytes

n0R.L

Explination

n0R   # A Stack of all numbers between 0 and the input converted to a number.
   .L # The length of the stringification of this.

Simple solution, works like a charm.

Try it online!

ATaco

Posted 2017-03-10T05:15:03.510

Reputation: 7 898

4

Mathematica, 48 47 46 bytes

-1 byte thanks to Martin Ender!

StringLength[""<>ToString/@Range[0,#,Sign@#]]&

Anonymous function, taking the number as an argument.

Shorter solution by Greg Martin, 39 bytes

1-#~Min~0+Tr@IntegerLength@Range@Abs@#&

numbermaniac

Posted 2017-03-10T05:15:03.510

Reputation: 639

1You can use Sign@# for #/Abs@#. – Martin Ender – 2017-03-10T08:01:41.080

1You can save a few bytes with a slightly different approach: 1-#~Min~0+Tr@IntegerLength@Range@Abs@#&. The initial 1 accounts for the digit of 0, while -#~Min~0 accounts for all the negative signs if the input is negative. – Greg Martin – 2017-03-10T08:23:57.840

4

PHP, 59 60 bytes

Outgolfed by Roberto06 - https://codegolf.stackexchange.com/a/112536/38505

Thanks to roberto06 for noticing the previous version didn't work for negative numbers.

Simply builds an array of the numbers, puts it to a string, then counts the digits (and minus sign)

<?=preg_match_all("/\-|\d/",implode(",",range(0,$argv[1])));

Run example: php -f 112504.php 8

ʰᵈˑ

Posted 2017-03-10T05:15:03.510

Reputation: 1 426

This doesn't work for a negative input, see here

– roberto06 – 2017-03-10T10:53:09.220

You could save 3 bytes using join instead of implode because it is an alias. – Mario – 2017-03-11T07:37:58.727

there is no need to escape the minus -1 Byte. On the other hand you can change your regex to [--9] – Jörg Hülsermann – 2017-03-11T13:37:43.257

4

Haskell, 39 38 bytes

f 0=1
f n=length$show=<<[0..n]++[n..0]

Try it online! Edit: saved 1 byte thanks to @xnor!

Explanation:

In Haskell for numbers a and b [a..b] is the range from a to b in 1-increments or 1-decrements, depending on whether b is larger a. So for a positive n the first list in [0..n]++[n..0] is [0,1,2,...,n] and the second one is empty. For negative n the second range yields [0,-1,-2,...,n] and the first one is empty. However if n=0 both ranges yield the list [0], so the concatenation [0,0] would lead to a false result of 2. That's why 0 is handled as a special case.

The =<<-operator on a list is the same as concatMap, so each number is converted into a string by show and all those strings are concatenated in one long string of which the length is finally returned.


Before xnor's tip I used [0,signum n..n] instead of [0..n]++[n..0]. signum n is -1 for negative numbers, 0 for zero and 1 for positive numbers and a range of the form [a,b..c] builds the list of numbers from a to c with increment b. Thereby [0,signum n..n] builds the range [0,1,2,...,n] for positive n and [0,-1,-2,...,n] for negative n. For n=0 it would build the infinite list [0,0,0,...] so we need to handle 0 as a special case, too.

Laikoni

Posted 2017-03-10T05:15:03.510

Reputation: 23 676

I think [0..n]++[n..0] should do for [0,signum n..n]. – xnor – 2017-03-10T13:31:57.553

4

Brachylog, 5 bytes

⟦ṡᵐcl

Try it online!

Builds the range [0,input], converts each number to string, concatenates into a single string and returns the length of the result

Leo

Posted 2017-03-10T05:15:03.510

Reputation: 8 482

I noticed TIO has an argument Z; what's up with that? Should it be in the count? – steenbergh – 2017-03-10T10:45:51.440

3@steenbergh: Leo's submission is a function, not a full program. Giving the argument Z to the Brachylog interpreter tells it to add an appropriate wrapper to make the function testable. (If you ran it as a full program, it wouldn't produce any output.) We allow either program or function submissions here, so that shouldn't count against the byte count, as it's not actually part of the submission. – None – 2017-03-10T11:00:44.073

4

PHP, 41 35 bytes

Saved 6 bytes thanks to user59178

Since ʰᵈ's answer was wrong for a negative input, I took it upon myself to build a new solution :

<?=strlen(join(range(0,$argv[1])));

This function :

  • Builds an array from 0 to $argv[1] (aka the input)
  • Implodes it with an empty character (i.e. transforms it to a string)
  • Echoes the length of the string

Try it here!

roberto06

Posted 2017-03-10T05:15:03.510

Reputation: 351

This is a nicer solution to mine, idk why I thought I had to do that preg_match() :( – ʰᵈˑ – 2017-03-10T11:13:43.923

Well, I wouldn't have thought of range() if it wasn't for your solution, I guess we're even ;) – roberto06 – 2017-03-10T11:21:19.027

1

you can save 3 bytes by using join() instead of implode(). it's an alias for the same thing. http://php.net/manual/en/function.join.php

– user59178 – 2017-03-10T15:10:40.513

1And 3 more by omitting the 'glue' parameter. – user59178 – 2017-03-10T15:18:36.210

I knew there was an alias for implode, but I didn't know I could omit the gue parameter. Thanks ! – roberto06 – 2017-03-10T15:29:05.547

4

R, 26 20 bytes

sum(nchar(0:scan()))

Very basic approach:

  • Make a vector 0:x

  • Count the characters in each value (will be coerced to a string automatically)

  • Sum

Not sure if there are any tricks to cut down the function definition? 6 bytes saved thanks to Giuseppe, by taking input from stdin instead.

user2390246

Posted 2017-03-10T05:15:03.510

Reputation: 1 391

you could do sum(nchar(0:scan())) instead and read n from stdin instead. – Giuseppe – 2017-05-15T16:24:56.343

3

Lua, 52 bytes

t=0;for i=0,io.read()do t=t+#tostring(i)end;print(t)

Iterates through a for loop from 0 - input, converts the integer i to a string and adds the length of the string to t before printing t

Josh

Posted 2017-03-10T05:15:03.510

Reputation: 1 021

3

QBIC, 25 bytes

:[0,a,sgn(a)|A=A+!b$]?_lA

Explanation:

:[0,a     Read 'a' from the cmd line, start a FOR loop from 0 to 'a'
,sgn(a)|  with incrementer set to -1 for negative ranges and 1 for positive ones
A=A+!b$   Add a string cast of each iteration (var 'b') to A$
]         NEXT
?_lA      Print the length of A$

steenbergh

Posted 2017-03-10T05:15:03.510

Reputation: 7 772

3

MATL, 11 bytes

0hSZ}&:VXzn

Try it online!

0h           % Implicitly input n. Append a 0: gives array [n 0]
  S          % Sort
   Z}        % Split array: pushes 0, n or n, 0 according to the previous sorting
     &:      % Binary range: from 0 to n or from n to 0
       V     % Convert to string. Inserts spaces between numbers
        Xz   % Remove spaces
          n  % Length of string. Implicit display

Luis Mendo

Posted 2017-03-10T05:15:03.510

Reputation: 87 464

3

Batch, 110 bytes

@set/a"n=%1,t=n>>31,n*=t|1,t=1-t*n,i=0
@for /l %%i in (0,1,9)do @set/a"t+=(i-n)*(i-n>>31),i=i*10+9
@echo %t%

Computes sum(min(0,abs(n)+1-10^k),k=0..9)+(n<0?1-n:1). (I only have to go up to 9 because of the limitations of Batch's integer arithmetic.)

Neil

Posted 2017-03-10T05:15:03.510

Reputation: 95 035

3

Python 2, 68 bytes

def f(i,j=1):
 if i==0:print j
 else:j+=len(`i`);f((i-1,i+1)[i<0],j)

Try it online!

Longer than but different from other Python solutions. Defines a recursive function called as e.g. f(10)

ElPedro

Posted 2017-03-10T05:15:03.510

Reputation: 5 301

3

PowerShell, 23 bytes

-join(0.."$args")|% Le*

Try it online! (will barf on TIO for very large (absolute) inputs)

Uses the .. range operator to construct a range from 0 to the input $args (cast as a string to convert from the input array). That's -joined together into a string (e.g., 01234) and then the Length is taken thereof. That is left on the pipeline and output is implicit.

AdmBorkBork

Posted 2017-03-10T05:15:03.510

Reputation: 41 581

The exact solution I had in my head when I read this question – briantist – 2017-03-11T03:57:05.573

3

Perl 6, 18 bytes

{chars [~] 0...$_}

Try it

Expanded:

{  # bare block lambda with implicit parameter 「$_」

  chars        # how many characters (digits + '-')
    [~]        # reduce using string concatenation operator &infix:<~>
      0 ... $_ # deductive sequence from 0 to the input
}

Brad Gilbert b2gills

Posted 2017-03-10T05:15:03.510

Reputation: 12 713

3

JavaScript, 50 bytes

Collaborated with @ETHproductions

n=>{for(t="";n;n<0?n++:n--)t+=n;alert(++t.length)}

Oliver

Posted 2017-03-10T05:15:03.510

Reputation: 7 160

3

Bash + GNU coreutils, 28

eval printf %s {0..$1}|wc -c

Try it online.

Digital Trauma

Posted 2017-03-10T05:15:03.510

Reputation: 64 644

3

Retina, 28 bytes

\d+
$*
1
$`1¶
1+
$.&
^-?
0
.

Try it online!

Explanation

\d+
$*

Convert the number to unary, keeping the sign untouched.

1
$`1¶

Each 1 is replaced by everything up to itself plus a newline. With this we get a range from 1 to n if n was positive, from -1 to n with an additional - at the start if it was negative. All numbers are in unary and separed by newlines.

1+
$.&

Convert each sequence of ones to the corresponding decimal number.

^-?
0

Put a 0 at the start, replacing the extra - if it's there.

.

Count the number of (non-newline) characters.

Leo

Posted 2017-03-10T05:15:03.510

Reputation: 8 482

3

Emacs, 20 bytes

C-x ( C-x C-k TAB C-x ) M-{input} C-x e C-x h M-=

The command itself is 20 keystrokes, but I need clarification on how this should be counted as bytes. I reasoned that counting each keystroke as 1 byte would be the most fair. The command above is written conventionally for easier reading.

Explanation

C-x (

Begin defining a keyboard macro.

C-x C-k TAB

Create a new macro counter. Writes 0 to the buffer; the counter's value is now 1.

C-x )

End keyboard macro definition.

M-{input} C-x e

After hitting META, type in your input number. The C-x e then executes the macro that many times.

C-x h

Set mark to beginning of buffer (which selects all of the text thus generated).

M-=

Run character count on the selected region. The number of characters will be printed in the minibuffer.

Example

Apologies for the terrible highlighting color. This is an example of using this command with the input 100. The output is in the minibuffer at the bottom of the screen.

Example execution with input of 100

cheryllium

Posted 2017-03-10T05:15:03.510

Reputation: 31

Yep, I'm pretty sure one keystroke is one byte. – NoOneIsHere – 2017-03-14T18:55:14.847

@NoOneIsHere There are two thoughts I had about that: 1) Can Ctrl+character be represented as a single byte? And 2) I see a lot of answers here counting Unicode chars as one byte, but they are not, so I thought maybe CodeGolf maybe has its own definition of "byte"? Thanks. – cheryllium – 2017-03-14T19:01:28.843

I really don't know. But you can ask on Meta.

– NoOneIsHere – 2017-03-14T19:05:23.217

2

Perl 5, 32 bytes

31 bytes of code + -p flag.

$\+=y///c for$_>0?0..$_:$_..0}{

Try it online!

Dada

Posted 2017-03-10T05:15:03.510

Reputation: 8 279

2

C#, 77 73 bytes

-4 bytes thanks to @Kevin Cruijssen

Lambda function:

(r)=>{var l="";for(int i=0,s=r<0?-1:1;i!=r+s;i+=s)l+=i;return l.Length;};

Ungolfed and with test cases:

class P
{
    delegate int numbers(int e);
    static void Main()
    {
        numbers n = (r) =>
        {
            var l = ""; 
            for (int i = 0, s = r < 0 ? -1 : 1; i != r + s; i += s)
                l += i; 
            return l.Length;
        };
        System.Console.WriteLine(n(8));
        System.Console.WriteLine(n(101));
        System.Console.WriteLine(n(102));
        System.Console.WriteLine(n(-10));
        System.Console.ReadKey();
    }
}

Mr Scapegrace

Posted 2017-03-10T05:15:03.510

Reputation: 221

You can change the while to for to save a couple of bytes: (r)=>{var l="";for(int i=0,s=r<0?-1:1;i!=r+s;i+=s)l+=i;return l.Length;}; (73 bytes) – Kevin Cruijssen – 2017-03-10T10:26:40.500

@Kevin Cruijssen You are right, thanks. – Mr Scapegrace – 2017-03-10T10:36:28.763

You can probably use an int counter and add the length inside the loop to save some bytes. If you compile to a Func<int, int> you can call the functions like r=>... to save 2 bytes (can probably do this anyway). – TheLethalCoder – 2017-03-10T13:10:54.820

2

JavaScript, 44 bytes

f=(n,i=1)=>n<0?f(-n)-n:n<i?1:n+1-i+f(n,i*10)
<input type=number oninput=o.textContent=f(+this.value)><pre id=o>

Neil

Posted 2017-03-10T05:15:03.510

Reputation: 95 035

2

REXX, 56 bytes

arg n
l=0
do i=0 to n by sign(n)
  l=l+length(i)
  end
say l

idrougge

Posted 2017-03-10T05:15:03.510

Reputation: 641

2

Jelly, 6 bytes

r0Ṿ€FL

Try it online!

Jelly's surprisingly bad at this, mostly because it doesn't have a dedicated builtin for stringifying integers; it does have a builtin for stringifying anything, but that means we can't have it autovectorize over lists.

Explanation

r0Ṿ€FL
r0      All numbers from {the input} to 0, inclusive
   €    For each of those numbers numbers:
  Ṿ       Find its string representation
    F   Concatenate the resulting strings
     L  Take the length of the resulting string

user62131

Posted 2017-03-10T05:15:03.510

Reputation:

The Length builtin doesn't work directly on integers? Preposterous! – ETHproductions – 2017-03-10T14:39:43.053

Wait, can you use D instead of Ṿ€? – ETHproductions – 2017-03-10T14:43:16.227

@ETHproductions: No, it doesn't deal with negative numbers correctly. – None – 2017-03-10T14:48:11.357

Ah, got it. And I guess there's no 0-byte way to add 1 to every number if the input is negative :P – ETHproductions – 2017-03-10T15:34:25.430

2

JavaScript (Node.js), 37 bytes

f=n=>n?(n+"").length+f(n>0?n-1:n+1):1

Port of my Python answer.

Try it online!

Dennis

Posted 2017-03-10T05:15:03.510

Reputation: 196 637

It's not only Node.js though, it should work on any platform that supports ES6. – ETHproductions – 2017-03-10T13:24:38.070

Yeah, I just used the auto-generated TIO answer. – Dennis – 2017-03-10T13:28:27.923

Oh cool, I didn't notice there was an option to do that :-) – ETHproductions – 2017-03-10T13:33:17.410

Yep, either with the mouse or by pressing Esc, S, G. – Dennis – 2017-03-10T13:40:58.737

2

Japt, 4 bytes

ò ¬l

Try it online!

Explanation:

ò ¬l
ò     // Creates a range from [0...Input]
  ¬   // Joins the array into a string
   l  // Returns the length

Oliver

Posted 2017-03-10T05:15:03.510

Reputation: 7 160

2

SQL (PostgreSQL), 76 bytes

SELECT sum(length(a::text))FROM generate_series(least(0,$1),greatest(0,$1))a

This is an SQL function.

Richard

Posted 2017-03-10T05:15:03.510

Reputation: 331

SQL! That's a rare one – tuskiomi – 2017-03-10T20:00:30.087

2

Java, 211 bytes

interface n{static void main(String[]a){int n=Integer.parseInt(a[0]),k=1,i;a[0]="";if(n<0)k=-1;for(i=0;i!=n+k;i+=k){a[0]+=i;if(i!=n)a[0]+=',';}System.out.print(a[0]);System.exit(a[0].replace(",","").length());}}

Takes number as first command line argument. Returns output as an error code:

Input: -10

0,-1,-2,-3,-4,-5,-6,-7,-8,-9,-10
Process finished with exit code 22

Ungolfed version with comments:

interface n {
    static void main(String[]a) {
        int n = Integer.parseInt(a[0]),                 // Input number 
        k = 1,                                          // For loop increment
        i;                                              // For loop counter
        a[0] = "";                                      // Empty string
        if(n < 0) k = -1;                               // If input number is negative loop increment is negative
        for(i=0; i != n + k; i += k) {                  // For loop
            a[0] += i;                                  // Append number to string
            if (i != n)                                 // If not the last number
                a[0] += ',';                            // Append comma
        }
        System.out.print(a[0]);                         // Output string
        System.exit(a[0].replace(",","").length());     // Return length of string without commas as error code
    }
}

cookie

Posted 2017-03-10T05:15:03.510

Reputation: 271

2

K, 29 Bytes

I have a feeling there is a better way...

f:{#,/$((+;-)x<0).(0;!1+abs x)}

(+;-)x<0     ---> Call this A. If x is less that 0, return - otherwise return +
(0;!1+abs x) ---> Call this B. A list; (0;the numbers from 1 to the absolute value of x)
A.B          ---> Apply A to B, e.g1. (-).(0;0 1 2) ==> 0 -1 -2 e.g2 (+).(0;0 1 2) ==> 0 1 2
,/$x         ---> $tring x (x is numbers asc or desc) and flatten the list ,/
#x           ---> Finally count the flattened list

Some tests...

  f 8
9
  f 10
12
  f 101
196
  f 102
199
  f -10
22
  f -100
293

Chromozorz

Posted 2017-03-10T05:15:03.510

Reputation: 338

{$[x<0;a;0]+#,/$!1+a:abs x} for 27 bytes. Sums up string of 0..abs[input], if input was negative then add the abs[input] as this is the number of - you'd need to print the string. – streetster – 2017-12-12T12:22:51.803

2

Clojure, 48 bytes

(count(apply str(range(min 0 %)(max 1(inc %)))))

(defn how-much-to-write? [n]
  ; Count the characters in the resulting string
  (count
    ; Basically "joins" the list with ""
    (apply str
      ; Creates an ascending/descending range, depending on the value of n
      (range (min 0 n) (max 1 (inc n))))))

Carcigenicate

Posted 2017-03-10T05:15:03.510

Reputation: 3 295

2

Stacked, 25 bytes

:sign\0\abs|>*''join size

Try it online!

Explanation

:sign\0\abs|>*''join size    stack: (n)
:                            stack: (n n)
 sign                        stack: (n sign[n])
     \                       stack: (sign[n] n)
      0                      stack: (sign[n] n 0)
       \                     stack: (sign[n] 0 n)
        abs                  stack: (sign[n] 0 abs[n])
           |>                stack: (sign[n] range[0, abs[n]])
             *               negates the range if negative
              ''join         said range as a single string
                     size    the desired length

Conor O'Brien

Posted 2017-03-10T05:15:03.510

Reputation: 36 228

2

Scala 75 Bytes

(x:Int)=>{
  val? =Math.abs _
  (0 to?(x))./:("")((a,c)=>a+","+c* ?(x)/x).size-1
}

I'm not sure how I can improve it any further. The Math.abs is really really annoying. I think there is probably a better way to go about doing the negative stuff.

Stefan Aleksić

Posted 2017-03-10T05:15:03.510

Reputation: 119

1

Javascript, 65 bytes

T=n=>{m=n>0?1:-1,o="";for(i=0;i!=n+m;i=i+m){o+=i}return o.length}

Kushal Bhabra

Posted 2017-03-10T05:15:03.510

Reputation: 99

1

Swift, 72 bytes

let f={i in(min(i,0)...max(0,i)).reduce(0){$0+"\($1)".characters.count}}

The "characters.count" really kills the score.

John McDowall

Posted 2017-03-10T05:15:03.510

Reputation: 161

1

Retina, 42 41 bytes

-(.+)
$*-¶$1
.+$
$*
\d|$
$%` 
(1*) 
$.1
.

Try it online!

Explanation

-(.+)
$*-¶$1

If the number is a negative, let's say -n (i.e. there is a - in the input), then replace the input with n -s, and n on the next line. In the end we just want to count the characters, and for -n as input, there will be exactly n - signs in the range.

.+$
$*

Convert the number at the end of string into unary.

\d|$
$%` 

Replace any digit character or the end of the string with all the text before it on the same line, plus a space. For a sequence of 1s, this results in  1 11 111 ... up until the original sequence. This builds the range from 0 to n, in unary.

(1*) 
$.1

Conversion back to decimal. Any series of 1s followed by a space is replaced with the number of 1s.

.

Count the matches of . and output it. . matches any single character except linefeed.

Business Cat

Posted 2017-03-10T05:15:03.510

Reputation: 8 927

1

Pip, 13 12 bytes

#J:^0\,a|a,1

Takes input from command-line argument. Verify all test cases at Try it online!

Explanation

Some weird tricks in this one:

0\,a is the inclusive range from 0 to a.

If a is negative, we want to take the inclusive range from a to 0 instead. A naive approach would be a ternary expression with a<0, but we can do better. The problem is that something like (0,-11) is a perfectly valid Range object and is truthy, even though the range it represents contains no numbers1. We want to convert it to an empty list (falsey).

To achieve this, we apply unary ^ to split the Range into characters. This operator works itemwise, so for example giving it 0\,10 would result in the list [[0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [1 0]]. Splitting into characters won't make a difference to the result, since we're going to join everything together anyway. But crucially, it forces the conversion of the Range into a List. So an input of -10 now results in the empty list [].

Now since [] is falsey, we can take the logical Or of the above with a,1 (i.e. range(a,1), not including the upper bound) and get the elements we want.

Next, we need to join them together. Unfortunately, Join has a higher precedence than Or, so we would need parentheses. But another approach is to modify Join with the compute-and-assign meta-operator : (which is like the = in += in C-like languages, but more flexible). This lowers the precedence of the operator such that parentheses aren't needed. Assigning to an rvalue is a warning, but not an error.

Finally, we take the length (#) of the resulting string, which is then autoprinted.

1 Such "backwards" ranges are used in string slicing, where the negative number means "the index 11 characters from the end."

DLosc

Posted 2017-03-10T05:15:03.510

Reputation: 21 213

1

C++ 102 Bytes

int f(int n){int o=0;std::string s;for(n=n<0?o=-n:n;n>=0;)s+=std::to_string(n--);return s.length()+o;}

Ungolfed

int f(int n)
{
    int o=0;
    std::string s;
    for(n=n<0?o=-n:n;n>=0;)
        s+=std::to_string(n--);
    return s.length()+o;
}

Will add explanations.

Wade Tyler

Posted 2017-03-10T05:15:03.510

Reputation: 261

Suggest int o=n<0?(n=-n):0;std::string s;for(;n>=0;) instead of int o=0;std::string s;for(n=n<0?o=-n:n;n>=0;) – ceilingcat – 2017-03-14T04:22:15.783

1

Pyth, 6 5 bytes

ljk}0
Uses ais523's Jelly algorithm, except that the range starts from 0.

Thanks to RK. for -1.

Erik the Outgolfer

Posted 2017-03-10T05:15:03.510

Reputation: 38 134

You could get rid of the M by just doing ljk}0 – RK. – 2017-03-11T22:16:10.347

@RK. And I knew there is a shorter way than s\M`! – Erik the Outgolfer – 2017-03-12T07:39:56.007

that's the feeling, right? – RK. – 2017-03-12T17:34:35.793

1

CJam, 15 bytes

ri_g\z),f*:`:+,

Try it online!

Explanation:

ri_g\z),f*:`:+, e# Accepts an integer from STDIN.
ri              e# Get integer from STDIN.
  _g\           e# Store the integer's sign behind it.
     z)         e# Take the absolute value and increment it, to make an
                e# implicit range.
       ,        e# Create range [0..N].
        f*      e# Multiply every integer in the range with the sign we
                e# stored earlier, so as to include the - signs.
          :`    e# Map repr.
            :+  e# Concatenate.
              , e# Length.

Erik the Outgolfer

Posted 2017-03-10T05:15:03.510

Reputation: 38 134

1

PHP, 38 35 bytes

<?=strlen(join(range(0,$argv[1]))); // 35 bytes
<?=strlen(join("",range(0,$argv[1]))); // 38 bytes

Useage: php file.php 8

The join is a little used alias of implode(), and php can easily join numbers together as a string. Titus commented that the glue isn't needed in join() if you want a empty string.

Martijn

Posted 2017-03-10T05:15:03.510

Reputation: 713

Save three bytes: The glue parameter for join is optional (see codegolf.stackexchange.com/a/86340/55735 and http://php.net/implode).

– Titus – 2017-03-13T12:38:30.643

1

Java 8, 80 bytes

Golfed:

n->{String r="";for(int i=0;i<=(n<0?-n:n);++i)r+=i;return r.length()-(n<0?n:0);}

Ungolfed:

public class HowMuchDoIHaveToWrite {

  public static void main(String[] args) {
    for (final int[] test : new int[][] { { 8, 9 }, { 101, 196 }, { 102, 199 }, { -10, 22 } }) {
      final int input = test[0];
      final int expected = test[1];
      final int actual = q(n -> {
        String r = "";
        for (int i = 0; i <= (n < 0 ? -n : n); ++i) {
          r += i;
        }
        return r.length() - (n < 0 ? n : 0);
      } , input);
      System.out.println("Input:    " + input);
      System.out.println("Expected: " + expected);
      System.out.println("Actual:   " + actual);
      System.out.println();
    }
  }

  private static int q(java.util.function.IntFunction<Integer> f, final int input) {
    return f.apply(input);
  }
}

user18932

Posted 2017-03-10T05:15:03.510

Reputation:

1

J, 20 bytes

(#":i.1+|p)-(p+|p)%2

Bijan

Posted 2017-03-10T05:15:03.510

Reputation: 781

Welcome to PPCG! By default, all answers to code golf challenges must be full programs or functions. Taking input from predefined varibales is not allowed. – Dennis – 2017-03-14T03:34:30.127

Sorry, I was unaware, I'll correct it as soon as I figure out a compact valid method. – Bijan – 2017-03-14T12:56:27.610

0

C#, 59 76 bytes

n=>string.Concat(System.Linq.Enumerable.Range(n>0?0:n,(n<0?-n:n)+1)).Length;

Longer than I wanted it to be because of the minus and Range takes a start and a count not start and end.

TheLethalCoder

Posted 2017-03-10T05:15:03.510

Reputation: 6 930

0

GolfScript, 33 bytes

~.abs),\.{.abs/}0if:S;{S*`,}%{+}*

Try it online!

Explanation:

~.abs),\.{.abs/}0if:S;{S*`,}%{+}* # Evals STDIN.
~                                 # Eval.
 .abs),\                          # Store an absolute value inclusive range behind the original integer.
        .{.abs/}0if:S;            # Store the integer's sign in S.
                      {S*`,}%     # After applying the input's sign, get the length of the string representation of every integer in the range.
                             {+}* # Sum.

Erik the Outgolfer

Posted 2017-03-10T05:15:03.510

Reputation: 38 134

0

Python, 63 bytes

lambda n:sum(map(len,map(str,range(*[[0,n-1,-1],[n+1]][n>0]))))

sagiksp

Posted 2017-03-10T05:15:03.510

Reputation: 1 249

0

Bean, 44 bytes

xxd-style hexdump:

00000000: 2653 4da0 6280 40a0 7852 a043 ccd0 80cc  &SM b.@ xR CÌÐ.Ì
00000010: a043 8b23 0020 8001 8b53 a062 4da0 4382   C.#. ...S bM C.
00000020: 53d0 80a0 1f20 8048 2043 253a            SÐ. . .H C%:

Equivalent JavaScript (adapted from @Dennis) (45 bytes):

(f=_=>A?(A+"").length+f(A-=Math.sign(A)):1)()

Explanation

Declares a recursive IIFE (immediately invoked function expression) f, using pre-initialized variable A with numeric input to count down and incrementally calculate the amount of characters in the range of numbers.

Try the demo here

Patrick Roberts

Posted 2017-03-10T05:15:03.510

Reputation: 2 475