[Boards: 3 / a / aco / adv / an / asp / b / bant / biz / c / can / cgl / ck / cm / co / cock / d / diy / e / fa / fap / fit / fitlit / g / gd / gif / h / hc / his / hm / hr / i / ic / int / jp / k / lgbt / lit / m / mlp / mlpol / mo / mtv / mu / n / news / o / out / outsoc / p / po / pol / qa / qst / r / r9k / s / s4s / sci / soc / sp / spa / t / tg / toy / trash / trv / tv / u / v / vg / vint / vip / vp / vr / w / wg / wsg / wsr / x / y ] [Search | Free Show | Home]

QUICK IN YOUR FAVORITE PROGRAMMING LANGUAGE, WRITE A PROGRAM

This is a blue board which means that it's for everybody (Safe For Work content only). If you see any adult content, please report it.

Thread replies: 321
Thread images: 26

File: 1467471847306.jpg (29KB, 412x430px) Image search: [Google]
1467471847306.jpg
29KB, 412x430px
QUICK

IN YOUR FAVORITE PROGRAMMING LANGUAGE, WRITE A PROGRAM THAT DETERMINES THE NUMBER OF DIGITS OF AN ARBITRARY INPUT INTEGER

OR THIS BIRD IS GONNA STAB YOU
>>
>>55513621
go fuck yourself
>>
holy shit can someone please kill this fucking bird?
>>
digitCounter(input);
/*Note from Pajeet
I got a pretty good start on the code but it needs some polishing*/
>>
File: 1467005968508.jpg (118KB, 853x600px) Image search: [Google]
1467005968508.jpg
118KB, 853x600px
>>55513621
emacs lisp
(defun count-digits (x base)
(cond ((= 0 x) 0)
(t (+ 1 (count-digits (/ x base))))))

(count-digits 1005 10) ;; => 4
(count-digits 84 10) ;; => 2
>>
>>55513621
Way too easy.
#include <math.h>
#include <stdlib.h>
#include <stdio.h>

int main(int argc, char *argv[])
{
if (argc != 2)
return 1;

char *endptr;
double n = fabs(strtod(argv[1], &endptr));

if (endptr == argv[1])
return 1;

if (n == 0.0)
printf("0\n");
else
printf("%.0f\n", log10(n) + 1.0);
}
>>
Public numDigits(string input)

Int digits = str.length(input)

Println(digits)


Something like that.
>>
How many times are you going to post this shitty thread?
>>
>>55513768
It's fun to see how other people think.
>>55513767
Same solution but in C.
>>
File: 1468103944456.png (811KB, 1069x1081px) Image search: [Google]
1468103944456.png
811KB, 1069x1081px
>>55513707
whoops forgot to accomodate only one digit
here...
(defun count-digits (x base)
(cond ((< x base) 1)
(t (+ 1 (count-digits (/ x base) base)))))

(count-digits 1000 10) ;; => 4
(count-digits 38 10) ;; => 2
(count-digits 4 10) ;; => 1
>>
File: image.png (260KB, 458x360px) Image search: [Google]
image.png
260KB, 458x360px
Chill out bird
>>
>>55513621
Okay, took about ten seconds:
int CountDigitsInInteger(int integer) {    
if(integer==0) return 1;
return 1+(int)(log10((double)integer));
}


Inb4 tons of code monkeys who can't into math produce ridiculous loop-based solutions.
>>
I'm hiring an Indian contractor now
>>
public int countDigits(int x)
return new String(x).length();
>>
Insert (dick_ass, (true))
>>
inp = raw_input("Enter an integer:")
try:
if '.' in inp:
raise Error
test = int(inp); print "Length:", len(inp)
except:
print "Not an integer."

dont stab me
>>
#include <stdio.h>

int main(void){
long long n;
int count = 0;
printf("Please input an integer value: ");
scanf("%lld",&n);

while(n!=0){
n/= 10;
++count;
}


printf("Digit count: %d",count);
}
>>
>>55513930
CountDigitsInInteger(0)
>>
File: ross-perot.jpg (15KB, 480x360px) Image search: [Google]
ross-perot.jpg
15KB, 480x360px
>>55513958

i kekd
>>
>>55513930
Fails in some cases due to floating point error.
>>
>>55513621
#include <iostream>

int main()
{
int num = 0;
std::cin >> num;
int digits = 1;
while ((num /= 10) != 0)
++digits;
std::cout << digits << std::endl;
}


or

#include <iostream>

int main()
{
int num = 0;
std::cin >> num;
if (num < 0)
num *= -1;
int val = 10;
int digits = 1;
while (val <= num)
{
val *= 10;
++digits;
}
std::cout << digits << std::endl;
}

Yet another method could use string streams.
>>
import java.lang.Math;

public int getDigits(int dubs)
return 1+log10(abs(dubs));
>>
>>55514032
>if(integer==0) return 1;

Are you retarded?
>>
>>55514077
Not him but, 0 is a digit. But he still is retarded because the next line returns the same.
>>
>>55514019
Input is not an integer. U gon get stabd.
>>
>>55514112
if it's not an integer it throws an error dont stab me pls
>>
>>55514099
>0 is a digit
By that logic, 010 is 3 digits long. Obviously, all leading zeros should be ignored.
0 is the "empty" number, and should be considered 0 digits.
>>
>>55514075
Shit, forgot to cast to int.
>>
>>55514129
Yes. But since an int can have the value 0, but not 030, it should be seen as a digit.
>>
>>55514032
You must not have looked very carefully at the code. Your test returns the correct result.
Maybe you didn't understand this cryptic looking line:
if(integer==0) return 1;


However, I do have to make this amendment:
int CountDigitsInInteger(int integer) {    
if(integer==0) return 1;
return 1+(int)(log10((double)abs(integer)));
}


>>55514057
Can you provide such a case?
>>
>>55514099
>because the next line returns the same
log(0) is undefined, goof.
>>
File: wall_e_eve-1600x900.jpg (430KB, 1600x900px) Image search: [Google]
wall_e_eve-1600x900.jpg
430KB, 1600x900px
>>55513707
Why is EVE capitalized like that
>>
>>55514019
def dont_stab_me(inp):
try:
if '.' in inp:
raise Error
test = int(inp); return len(inp)
except:
return None

function
>>
>>55514167
Depends on the language, but 1+ undef = 1 sometimes. Wouldnt trust it, but yeah you're right.
>>
>>55514178
eeeeeevaaaaaaaaa!
>>
>>55514149
>But since an int can have the value 0, but not 030
You don't seem to understand how numbers actually work. 03 and 3 are just different representations of the same number.
>>
File: 1449551937430.jpg (52KB, 233x233px) Image search: [Google]
1449551937430.jpg
52KB, 233x233px
function digitCount(num){
return String(num).length
}


ez


inb4 error handling
>>
program asd;
var
i:integer;
s:string;

begin
readln(i);
str(i,s);
writeln(length(s));
end.
>>
>>55514190
You dont seem to understand how integers work. 0 is an integer, but 030 is not, as it will be made 30.
>>
>>55514199
what programming language is this?
>>
>>55514156
Not the floating point guy, but, never. Ints cut off the number, not round off. Which this solution relies on.

Floating point errors is when e.g. 0.1 is expected but 0.99999999... is returned. Which doesnt matter in this case.
>>
>>55514208
>but 030 is not
Yes it is, idiot. You seem to be confusing numbers with their string representation.
"30" and "030" both represent the thing that is "thirty".

By your dumbass logic: in
int x = 30;
, x doesn't equal 30 either.
It equals 11110 (base 2), because "30" not how it's actually stored.
>>
>>55513621
lambda x: len(str(x))
>>
>>55513930
Have you benchmarked the code and determined that calling log10 is actually faster than (at most) 10 iterations of a loop dividing by 10 though? I'm actually curious, I never did it myself and don't know what log10 does internally.
>>
>>55514285
Doesn't take into consideration a float
>>
>>55514249
Yes, I was intentionally using the int cast as a floor function.
I honestly have no idea what floating point guy was talking about.
>>
>>55514291
No, and I have to admit that there's a very good chance calling log10 would be slower. But since this is a programming puzzle (in the loosest sense of the word,) a more elegant and math-y solution like mine seems more appealing.
>>
print('Your number has ' + str(len(str(int(input('Type a number> '))))) + ' digits')
>>
>>55514262
Op specified that the input is an integer. Hence I assume that 030 will be seen as 30 in this case. And we're talking decimals, not binary..

If someone is asking the amount of digits of number 3, you wouldnt say 100000000 right? Because you could just add that many 0s.

Thats my POV on this shitty assignment.
>>
im gay
>>
>>55514305

>IN YOUR FAVORITE PROGRAMMING LANGUAGE, WRITE A PROGRAM THAT DETERMINES THE NUMBER OF DIGITS OF AN ARBITRARY INPUT INTEGER


>THE NUMBER OF DIGITS OF AN ARBITRARY INPUT INTEGER

>INPUT INTEGER

>INTEGER
>>
>>55514314
He's probably just sperging out anything he knows to sound smart.
>>
heheuhad haha lollolo :-)

:=====)))
;)))
;(
;(
;(
:))))
:)
>>
>>55514379
if you do int() on a float it will convert it, but that is not the number that was input.
>>
File: absolutetruth.jpg (29KB, 724x211px) Image search: [Google]
absolutetruth.jpg
29KB, 724x211px
>>55514359
>>55514262
math.stackexchange has spoken.
>>
>>55514384
Damn you messed up on ;(, it can cause ()'; errors.
>>
<?php
$int = 123;
echo strlen($int);


int n = 123;
Console.Log(n.ToString().Length);
>>
>>55514400
Im the guy thats on-par with stackexchange, but what about values like 03.
>>
>>55514420
That is the number 3, and it has one digit.
>>
File: bird stealing knife.gif (2MB, 300x173px) Image search: [Google]
bird stealing knife.gif
2MB, 300x173px
>>55513659
I steal his knife every thread but eh keeps coming back.
>>
>>55513621
5 print "type an integer"
10 input a%
15 if a<0 then a=-a
20 r%=len(str$(a%))-1
25 print "digits: ";
30 print r%;

biggest issue with this is that the integer range is a signed 16-bit number on the C64, so it'll max out at 5 digits (32767)
would have used log10 to get this, but C64 BASIC is missing a ton of math shit that I wish it had
although, thinking about it more, I guess I'd have still done it this way if I did this in C
>>
>>55513621
Hasty solution.
EXTERN scanf
EXTERN printf

SECTION .data
input: DB "%d", `\0`
output: DB "Has %d digits", `\n`, `\0`
number: DD 0
SECTION .text
GLOBAL _start

_start:
mov rdi, input
mov rsi, number
call scanf

mov eax, [number]
mov ebx, 10
xor ecx, ecx
find_digits:
cdq
idiv ebx
add ecx, 1
test eax, eax
jnz find_digits

mov rdi, output
mov esi, ecx
call printf

mov eax, 1
mov ebx, 0
int 80H
>>
>>55514457
>tfw just realized that line 15 is entirely useless since when displayed as a string, the first character of an integer is a space if positive and a - if negative, so I don't need to futz around with adjusting the sign to match

also, "a" (float) is a different variable from "a%" (int)
>>
>>55514400
That's stupid.
Thinking in terms of natural numbers and thinking of them as "number of things", 0 is the empty amount, and should be 0 digits.

Another way of thinking about it to using a formula.
To find the amount of natural numbers (including zero) that have some number of digits (n), the formula would be
digits(n) = 10^n - 10^(n-1)

Since we're dealing with integers here, in the 0 case
10^(-1) = 0
because of truncation.
So
digits(0) = 10^0 - 0 = 1

So there is 1 natural number (incl 0), there is 1 number with 0 digits, which is 0.
>>
>>55513621
function hereIsYourHomeworkAnon (x) {
x = parseInt(x);

if (isNaN(x)) {
return 0;
}

return x.toString().length;
}


All too easy.
>>
>>55513621
var countDigits = require('count-digits');
console.log(countDigits(process.argv[2]))
>>
>>55514029
This is how i would do as well, except the loop condition being n > 9
>>
>>55514761
>>
File: 1462411508798.jpg (17KB, 480x352px) Image search: [Google]
1462411508798.jpg
17KB, 480x352px
>tfw coding in C#
>plan was to using fucking modular division to see the length of the string
>in C# of all things

holy shit I am retarded
>>
>>55514598
>0 is the empty amount, and should be 0 digits.
Are you trolling? You're advocating a system where it's impossible to describe 0 using digits? Sounds like a step backwards.

The representation of 0 in the common, universally used decimal number system, requires exactly one digit, and that's 0.
Leading 0s are not part of the standard number system.
Of course there are an infinite number of other ways to represent numbers, using whatever leading digits you want. But no one does that, and that's clearly not what OP wanted.
>So there is 1 natural number (incl 0), there is 1 number with 0 digits, which is 0.
Sounds like your formula is wrong then.
>>
#include <stdio.h>

int main(void){
long long n;
int count = 0;
printf("Please input an integer value: ");
scanf("%lld",&n);

while(n!=0){
n/= 10;
++count;
}


printf("Digit count: %d",count);
}
>>
>>55514598
You're wrong though, 0 has one digit. Let us consider an integer in base 10, for example 123. We can express that integer (and any other finite integer) as a set containing the digits used to represent that integer, in this case the set {1,2,3}. Each element of the set corresponds to a single digit, so the cardinality of the set used to represent the integer is equivalent to the number of digits in the integer. In base 10 the number 0 is represented as 0, we would represent it as the set {0}. The cardinality of the set {0} is one because the set contains one element. Therefore the number 0 has one digit.
>>
>>55513621
digitLength <- function(x){
if(!is.numeric(x) || !(x==as.integer(x))){
stop("non-integer argument")
}else{
string <- strsplit(as.character(abs(x)), split = "")[[1]]
}
length(string)
}
>>
>>55513621

auto byDigit(BigInt n)
{
static struct Result
{
BigInt n;
bool empty = false;

@property int front() { return n % 10; }
void popFront() { n /= 10; empty = n == 0; }
}

return Result(n);
}

import std.algorithm;
import std.stdio;
import std.exception;
import std.bigint;

void main(string[] args)
{
enforce(args.length > 0, "No number passed");
auto num = BigInt(args[1]);
writeln(num.byDigit.count);
}
>>
>>55513621
function getNumDigits(val) {
var numDigits = 0;
while (val % 1 == 0) {
numDigits++;
val /= 10;
}
return numDigits;
}

Wrote it in Python first but then rewrote it in Javascript when I remembered that Python is shit.
>>
>>55513621
class CountDigitsCommandlet extends Commandlet;

event int Main( string Parms )
{
if(string(int(Parms))!=Parms)
{
Log("Invalid input. Only integers are accepted.");
return 0;
}
Log(Len(Parms));
return 0;
}
>>
>>55514396
Hey bud I don't know if you're trolling at this point

buttttttttttt

decimals(floats) are not integers(-3,-2,-1...5,6,7)
>>
>>55515176
Sorry I made an error, it should be:
function getNumDigits(val) {
if (val == 0)
return 1;

var numDigits = 0;
while (val % 1 == 0) {
numDigits++;
val /= 10;
}
return numDigits;
}
>>
>>55514974
>You're advocating a system where it's impossible to describe 0 using digits?
It can describe zero perfectly. Zero has zero digits.
>The representation of 0 in the common, universally used decimal number system, requires exactly one digit, and that's 0.
Zero is just a place holder for blank. Having a number which is entirely blank isn't particularly helpful though, so we represent it with '0'.

In the cases when zero isn't the leading number, it does count as a digit though.
In "10", the zero in the ones column does have a value. There are 10 ones, but we write it down as '0'.
>Sounds like your formula is wrong then.
Explain how. It works in the general case, so why doesn't it work in the zero case?
>>
>>55515256
see
>>55515009
>>
>>55513621
Why can't I just do len(str(input()))?
>>
>>55513621
#include <stdlib.h>
#include <math.h>
int main(int argc, char* argv[]) {
return 1 + (int)log10(llabs(strtoll(argv[1],NULL,10)))
}
>>
>>55515302
>>55515009
Again, '0' is a placeholder for blank.
The set for zero is {}, but for the sake of convenience, we write this empty set as '0'.
I'm arguing this from a mathematical point, not a "what humans write down" point.
>>
>>55515316
What happens if I input 000000015? It'll say 9 digits.
>>
>>55514210
Pascal
>>
>>55515316
not sure what language, but my guess is negatives and leading zeroes. And detecting non-integers.
>>
import java.util.Scanner;
public class DigitFinder {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int given, check = 10, count = 1;
System.out.print(">");
given = sc.nextInt();

while(check <= given) {
check = check * 10;
count++;
}

System.out.println("Your digit is " + count + " digits big");
}

}
>>
>>55513621
print(len(input()))
>>
numberdigits =: (((1&+)@(<.)@(10&^.))@(([)`(_1&*)@.(<&0)))`([)@.(0&=)
>>
>>55515316
That's not solving the problem described in the OP. You're supposed to accept an arbitrary input integer, not an arbitrary input string.
>>
>>55513621
import re
string = input( "enter an integer: " )
digits = len( re.findall( '[0-9]', string ) )
print( 'not a number' if len( string ) - digits else digits )
>>
>>55515326
If you're going to use command line arguments couldn't you just do this
]#include <stdio.h>
#include <string.h>
int main(int argc, char **argv){
printf ("%d\n", strlen(argv[1]));
}
>>
>>55515256
>It can describe zero perfectly. Zero has zero digits.
Okay, that's an interesting idea. But that's not the way our commonly used number system works. The digit 0 refers to an empty quantity. It's a symbol with a well established meaning.
I feel like /sci/ needs to settle the question once and for all, though.
>>
>>55515554
Again, I'm not talking about "how we write shit down".
>>
>>55515590
Okay, but that's what the OP was asking for. That's the whole point of digits.
>>
>>55515337
>>55515355
len(str(abs(int(input()))))
>>
>>55513621
#include <stdio.h>

int main(){
int n,count=0;
scanf("%d",&n);
while(n > 0){
n /= 10;
count++;
}
printf("%d\n",count);
}
>>
>>55515430
see >>55515337
>>
>>55515712
ought to do it. Although if int coerces all numeric input to integer then is still processes invalid input. Btw I don't know any "real" programming languages so sorry if I'm retarded.
>>
int num_digits(int n)
{
return snprintf(NULL, 0, "%d", n);
}
>>
>>55513621
int countDigits(int num, int radix) {
int temp = num;
int count = 0;
do {
++count;
temp /= radix;
} while (temp != 0);
return count;
}
>>
>>55513621
def digs(n):
if not n:
return 1
d = 0
while n:
n /= 10
d += 1
return d
>>
>>55513736
>no return 0
sloppy c, would not use, 0/10
>>
>>55513621
sub digits {
my ($str) = @_;
$str =~ m/^([0-9]+)/;
return length $1; }

while(<>) {
print digits $_, "\n";
}
>>
>>55515999
>sloppy c
Reaching the end of main() guarantees a return 0, granddad.
>>
>>55515936
Or recursively for fun

int countDigits(int num, int radix) {
int temp = num / radix;
return temp == 0 ? 1 : countDigits(temp, radix) + 1;
}
>>
File: staaaaab!.png (4KB, 557x148px) Image search: [Google]
staaaaab!.png
4KB, 557x148px
>>55515712
>>
>>55516129
>>55515936
Of course assuming that radix > 1
>>
Public int digits(Integer i){
return i.toString(). length;
}
>>
>>55513967
Remember to take the absolute value of x.
>>
test
>>
>>55513621
Look at the number how many digits does it have

brain
>>
#include <iostream>

int main() {

int number = 0;
int ten = 10;
int count = 0;

std::cin >> number;

while(number%ten != 0) {
ten = ten * 10;
count++;
}

std::cout << count;

}
>>
hi
>>
countDigits :: (Integral a) => a -> a
countDigits x
| x == 0 = 0
| otherwise = 1 + countDigits (div x 10)
>>
>>55516582
Whoops.

 count 
should start at 1 and there should be a return.
>>
>>55516582

SHE PLUSH PLUSH
>>
public int DigitsWithinInt(int fuckballs)
{
var s = $"{fuckballs}";
return s.Length;
}


mmm... comfy edition
>>
>>55516670
$"{fuckballs}"  change to
$"{Math.Abs(fuckballs)}"
>>
#/usr/bin/env python

print(len(input("enter number: ")))

>>
countDigits :: (Integral a) => a -> a
countDigits x
| x == 0 = 0
| otherwise = (1+) . countDigits . fromIntegral . abs $ (div x 10)
>>
>>55516731
enter number: 00000050
8
>>
File: yousuck.png (1KB, 342x76px) Image search: [Google]
yousuck.png
1KB, 342x76px
>>55516731
>>
>>55516731
Fails for negative numbers, too. Poor showing.
>>
>python
len(str(n))
>>
len(str(i))

:^)
>>
>>55517126
>>55517192
Why are you guys posting an incorrect solution that's already shown up in the thread?
>>
>>55514019
>>55514331
>>55515428
>>55515712
>>55515956
>>55516731
>>55517126
>>55517192
>every pythonfag except one decided to solve the problem by fucking around with strings
>>
>>55513736
>if(n == 0.0)
>no return 0

horrible C coding. Kill yourself, I bet you are some of these coding bootcamp faggots
>>
>>55517261
And that's a correct approach since
> AN ARBITRARY INPUT INTEGER
may have an arbitrary number of leading zeroes and conversion to int will discard them.
>>
>>55517281
The coding bootcamp tards probably all wrote len(str(i)) in python.
>>
>>55513621
the really shitty and lazy way
unsigned char numint(int in){
char temp[16];
sprintf(temp, "%i", in);
return strlen(temp);
}
>>
>>55517307
and then to determine the number of digits you convert back to a string and apply len()?
why?
>>
>>55517323
Also true sir

*tips fedora*
>>
>>55513621
p gets.chomp.to_i.to_s.length
>>
>>55517340
No. The input is a string in the first place.
>>
>>55514505
i lol'd
>>
>>55514505
Assuming that works, props.
>>
>>55514505
>uses x64 calling convention
>uses x86 calling convention at end
>uses x86 interrupt instead of x64

WTF
>>
>>55517386
>
len(str(int(raw_input())))

this was the basic structure
raw_input() is string, convert to int, convert back to string, and evalutate character length
that is your algorithm, and it is shitty
>>
>>55515428
import re
string = input( "enter an integer: " )
print( 'not a number' if re.search( '^[-+]?[0-9]*$', string ) == None else len( string.split( '-' )[ -1 ].split( '+' )[ -1 ] ) )

fixd
>>
>>55513621
private void numberLength(int num)
{
String toCount = Integer.toString(num);
System.out.print(toCount.length());
}
>>
>>55514285
doesn't take into consideration negative numbers

lambda x: len(str(x))-1*(x<0)
>>
>>55517511
It's in java. I know, fuck me right
>>
>>55517474
Nope. Mine was >>55515428 .
And I'm not telling you that those len(str(n)) "solutions" are god, I'm telling you that the string without conversion approach is correct.
>>
>>55517531
and you didn't convert to int, so leading zeroes are retained. this is not correct
>>
>>55517550
>leading zeroes
You're a goddamn faggot Harry
>>
>>55517558
>00003 is a five digit number
>>>/school/
>>
>>55517281
>if(n == 0.0)
The log10 function doesn't work properly if n == 0, so it's taken out as a special case.
Sure, you can do your !n shit, but that really doesn't get the point of this floating point comparison across.
>no return 0
The return 0 is implicit, and has been for fucking 17 years. God damn, get with the fucking times.
>>
>>55513621
>NUMBER OF DIGITS OF AN ARBITRARY INPUT INTEGER

const numDigits = (int) => 1


mfw literally everyone in this thread is a complete retard.
>>
>>55517261
does converting an integer to a string an especially complex operation in the language you use?
>>
>>55517550
> THE NUMBER OF DIGITS OF AN ARBITRARY INPUT INTEGER
Well this can be interpreted as 'number of digits in arbitrary INPUT of a valid integer' or 'number of digits in RESULTING INT of an arbitrary input'. So lets just agree that bird is trolling today.
>>
>>55517676
no, it's just messy
>>
>>55517688
00003 is a valid integer. It's just not an its canonical form.
Just face it, your code is shit and you are shit.
>>
>>55513621
python.

number = 0
if number == 0:
print('length is 1')

you said arbitrary integer.
>>
>>55517755
>length is 1
And you even managed to fuck that one integer up.
>>
>>55517691
really? conceptually it seems like a very tidy solution to all sorts of weird edge cases that you might need to think about if you keep the value as a mathematical value, but become trivial when it's just a string.

the premise of the OP's question is to treat the number as a thing where you count the individual glyphs. languages tend not to be designed to reason about numbers that way, but strings are. sometimes they're just thought of as (indexible) arrays of characters. that's exactly the kind of framing you want for this question.

you can claim that turning something from an integer to a string is messy, but in python it's not implemented as such. it's just `str(someInt)`. if other languages don't facilitate casting very smoothly, then that's too bad
>>
>>55514598
>0 is the empty amount
uh, okay sure
>and should be 0 digits
not sure how you got from step 1 to step 2 buddy

what is a digit? a number 0-9.
define the number of digits in an integer (in the decimal number system) to be the least amount of digits necessary to represent it in the decimal number system.
there, problem solved. everyone agrees with this definition.
>>
function count(n:Int):Int
var i = 0;
while(true)
{
if (Std.string(n).length == i)
{return i;}
}

;)
>>
#include <stdio.h>
#include <ctype.h>

int main()
{
char number[256] = {0};
int digits = 0, i = 0;

fgets(number, sizeof(number), stdin);

if (number[0] == '\0')
{
puts("you entered an empty string pajeet");
return 1;
}

if ((number[0] == '-' || number[0] == '+') && number[1] != '\0')
i++;

while (number[i] != '\0' && number[i] != '\n')
{
if (isdigit(number[i]))
digits++;
else
{
puts("that's not a number pajeet");
return 1;
}

i++;
}

printf("the number has %d digits pajeet\n", digits);
return 0;
}

>>
countdigits n | abs n < 1 = 0 | otherwise = 1 + countdigits (n / 10)


> not using haskell
> not solving all problem with one line of code
> not getting it right the first time

scrubs
>>
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
if (argc != 2)
return printf("Usage: ./digits n\n");

int n = atoi(argv[1]);

if (n < 0)
n *= -1;

// zero has one digit
int i = 1;
while (n /= 10)
{
i++;
}
printf("%d\n", i );

return 0;
}
>>
>>55516383
Good point.
>>
File: Cshaper.jpg (7KB, 274x78px) Image search: [Google]
Cshaper.jpg
7KB, 274x78px
Generics anyone?
>>
static int fuckoffbird(int x) {
int digits = 0;
do digits++; while ((x /= 10) > 0);

return digits;
}
>>
>>55513621
main = getLine >>= print . length

pls bird, no stabbey
>>
print length <>

Easy
>>
>>55513930
log10(-10) =?????
>>
>>55513621
C:
         int i=1;
unsigned int n=79842534;
int j=0;

for(; (n)>(n%(i));i*=10,++j){}


n is the number evaluated j has the number of digits works only for positive integers.

Matlab:
 length(int2str(n)) 
>>
File: Cshapest.jpg (50KB, 780x369px) Image search: [Google]
Cshapest.jpg
50KB, 780x369px
Fixed it, should work with integers in strings
>>
>>55513621
#![feature(io)]
use std::io::{stdin, Read};

fn main(){
let i: String = stdin().chars()
.map(|c| c.unwrap())
.skip_while(|c| c.is_whitespace())
.take_while(|c| !c.is_whitespace())
.collect();
if i.chars().all(|c| c.is_alphanumeric()) {
println!("{}", i.chars().count())
}else{
println!("Not a number.")
}
}


Supports integers of any base(as long as they use numerical or alphabetical chars), any length written using any numerical or alphabetical unicode characters.
>>
>>55519748
>#![feature(io)]
Are you using a ridiculously old version of Rust or some shit?
>>
>>55519771
Nope, it just turned unstable for some reason.
https://github.com/rust-lang/rust/issues/27802
$ rustc rust.rs
rust.rs:5:29: 5:34 error: use of unstable library feature 'io': the semantics of a partial read/write of where errors happen is currently unclear and may change (see issue #27802)
rust.rs:5 let i: String = stdin().chars()
^~~~~
rust.rs:5:29: 5:34 help: add #![feature(io)] to the crate attributes to enable
error: aborting due to previous error
$ rustc --version
rustc 1.11.0-dev
>>
>>55513621

Meh, too easy.

Here, I give you a choice:

a = "and 1 and 2 and 1234"

# result: "121234"
s1 = a.gsub(/[^0-9]/, '')
s2 = a.gsub(/[^\d]/, '')
s3 = a.gsub(/\D/, '')
s4 = a.tr("^0-9", '')
s5 = a.delete("^0-9")

# result as array: ["1", "2", "1234"]
s6 = a.scan(/\d+/)
s7 = a.split(/[^\d]/).reject &:empty?

# result as array: ["1", "2", "1", "2", "3", "4"]
s8 = a.chars.grep /\d/
s9 = a.chars.select {|s| s =~ /[0-9]/}
s10 = a.chars.reject {|s| s !~ /[0-9]/}

# amount of digits
local_variables.each {|s| eval "p #{s}.length" if s[0] == "s"}
>>
int getLength(int v){
int length = 0;
for(int i = v; i > 0; i/=10}
length++;
return length;
}
>>
>>55519667
If (condition) {boolean = true}
can be written as
boolean = (condition)
>>
>>55519862
boolean = (condition)
can be written as
boolean = (condition) ? true : false
>>
echo "${#x}"
>>
>>55519900
Yes, but he's setting a boolean. So he could just set it. No need for a short if.

You wouldnt do
boolean = (condition) ? true : false;

You would go
Boolean = (condition);
>>
>>55519829

Damn, I didn't noticed that it should be an integer..

Very well:
i = 2364225274

# "easy to use" version
p i.to_s.size

# faster version
cnt = 0

while i > 0 do
i /= 10
cnt += 1
end

p cnt

>>
(length . show . abs) (666)
>>
>>55514019
>:")
>>
>>55513621
template <typename T, typename std::enable_if<std::is_integral<T>::value>::type>
static const std::size_t get_number_of_digits(const T n) noexcept
{
const std::string s = std::to_string(n);
if(n < 0)
return s.size() - 1;

return s.size();
}
>>
>>55520752
>(length . show . abs)
that's nice, i was wondering what the point-free version of
>>55518174
>countdigits n | abs n < 1 = 0 | otherwise = 1 + countdigits (n / 10)
would look like,
but using show and then taking the lengthe feels like cheating, but hey it's functional, it does typecheck and i now works for everything that has derivces show. good job
>>
>>55520752

Hah, in Ruby you could write it like this:

666 . abs . to_s . length


It's kinda wierd, but often I write a solution in Ruby and then I see a Haskell solution and think "cool, this is how I should do it!".
>>
MATLAB
ceil(log10(input+1));
>>
#!/usr/bin/env bash
n=$*
[ -z "$n" ] && read n
printf '%d\n' ${#n//[^0-9]/}
>>
>>55513621
def calmdownbird(n):
nlen = len(str(n))
print(nlen)
>>
import math
def fuckbirds(n):
lenn = int(1 + math.log10(n))
print(lenn)
>>
print(len(int(input("type number"))))


:~)
>>
>>55521365
shit this is creative, thanks anon
>>
int count(int in)
{
if(!in) return 0;
return count(in/10)+1;
}


Something like this, i'm obviously not going to test it
>>
>>55513621
post the webm with the smoking bird
>>
>>55513621
Length[IntegerDigits[#]] &

ez
>>
>>55520752
why not just
 (length . show) 
>>
>>55522628

"An arbitrary integer" can be negative.

If you just calculate the length of the string, "-11" will result in 3, but has only 2 digits..
>>
>>55513621

Sub digits(i As Integer)
MsgBox Len(CStr(i))
End Sub
>>
>>55513621
def countDigits(number):
return len(str(number))

number = int(input("Insert a number: "))
print("Digits: %d" % countDigits(number))
>>
>>55523197
Better yet


def countDigits(number):
return len(str(number)) - 1 if number < 0 else len(str(number))

number = int(input("Insert a number: "))
print("Digits: %d" % countDigits(number))

As >>55523038 have said.
>>
>>55514755
>>55523038
Fuck me, how do numbers work?

function hereIsYourHomeworkAnon (x) {
x = parseInt(x);

if (isNaN(x)) {
return 0;
}

return Math.abs(x).toString().length;
}
>>
>>55514127
raw_input returns a string type you nigger
>>
>>55517513
Doesn't take floats into account
lambda x: len(str(x)) - 1*(x<0) - 1*(type(x) is float)
>>
,[>+<[-],]>>++++++++
++<[->-[>+>>]>[+[-<+
>]>+>>]<<<<<]>>>[>++
++++++[-<++++++>]<.[
-]]++++++++[-<++++++
>]<.
>>
File: 1443526747771.gif (2MB, 640x352px) Image search: [Google]
1443526747771.gif
2MB, 640x352px
>>55523487
>Doesn't take floats into account
>>55513621
>INTEGER
>>
>>55523535
Welp I didn't read that right. This would usually mean failing the interview for not being able to follow directions, right?
>>
>>55523552
If the interviewer was an asshole, and was planning on tripping you up over something trivial, yes.
>>
>>55513621
#include <iostream>

int main() {
int n;
std::cout << "Please enter an integer:\n";
std::cin >> n;
int i = 10;
int digits = 1;
while (n >= i) {
i *= 10;
digits++;
}
std::cout << "The number of digits is " << digits << "\n";
return 0;
}
>>
>>55513621
foo = input('    > ')
try:
foo = int(foo)
foo = str(foo).split()
if '.' not in foo[0]:
foo.append(' '.join(foo[0]))
foo.pop(0)
foo = foo[0].split(' ')
print len(foo)
else :
print 'nigger'
except ValueError :
print 'input is not an integer'
>>
>>55513621
R=input ("Name an arbitrary integer")
print(len (r))
>>
File: eOK8CCZ.png (24KB, 944x278px) Image search: [Google]
eOK8CCZ.png
24KB, 944x278px
>>55513621
C#, plus IntelliSense notes

static void Main(string[] args)
{
WriteLine(NumberOfDigitsFromIntegerAbstractFactoryInterfaceBean(456480));
WriteLine(NumberOfDigitsFromIntegerAbstractFactoryInterfaceBean(0));
WriteLine(NumberOfDigitsFromIntegerAbstractFactoryInterfaceBean(1111111111));

ReadLine();
}

/// <summary>
/// This method accepts an integer and returns a count of the digits comprising that integer.
/// </summary>
/// <param name="input">The integer that is to be evaluated for its digit count.</param>
static int NumberOfDigitsFromIntegerAbstractFactoryInterfaceBean(int input)
{
return (input == 0 ? 1 : (int)Math.Floor(Math.Log10(input) + 1));
}
>>
>>55523614
doesn't work you pleb, you can't determine the length of an integer with len()
>>
>>55523630
kek
>>
>>55513621
spam = input('int : ')
foo = 0
while spam > 0:
spam /= 10
foo += 1
print foo
>>
divide and conquer:
n<1E5?n<1E2?n<1E1?1:2:n<1E3?3:n<1E4?4:5:n<1E7?n<1E6?6:7:n<1E8?8:n<1E9?9:10;

for unsigned. Add
n=n<0?-n:n;
for signed
>>
>>55523806
wut?
>>
>>55523831
Let's use your post number which has 8 digits
       n<1E5?n<1E2?n<1E1?1:2:n<1E3?3:n<1E4?4:5:n<1E7?n<1E6?6:7:n<1E8?8:n<1E9?9:10;
55523831<1E5?n<1E2?n<1E1?1:2:n<1E3?3:n<1E4?4:5:n<1E7?n<1E6?6:7:n<1E8?8:n<1E9?9:10;
false?n<1E2?n<1E1?1:2:n<1E3?3:n<1E4?4:5:n<1E7?n<1E6?6:7:n<1E8?8:n<1E9?9:10;
n<1E7?n<1E6?6:7:n<1E8?8:n<1E9?9:10;
55523831<1E7?n<1E6?6:7:n<1E8?8:n<1E9?9:10;
false?n<1E6?6:7:n<1E8?8:n<1E9?9:10;
n<1E8?8:n<1E9?9:10;
55523831<1E8?8:n<1E9?9:10;
true?8:n<1E9?9:10;
8
>>
>>55523806
>>55523880
That's some pretty dumb shit, friend.
>>
>>55513621
Does it only contain numbers?

Anyways
isIn :: [Char] -> Char -> Bool
isIn [] _ = False
isIn (x:xs) ch = if x == ch then True else (isIn xs ch)

amount :: [Char] -> Integer
amount [] = 0
amount (x:xs) | isIn numbers x == True = 1 + amount xs
| isIn numbers x == False = 0 + amount xs

main = do
input <- getLine
numbersInInput = amount input
print numbersInInput


Now go fuck yourself birdie
>>
>>55523969
Fuck forgot to define numbers.
>>
>>55523950
That's 10 times faster than any other solution in this thread, friend.
>>
let f = n => ("" + Math.abs(n)).length;
f(42);


Very inefficient (string building just to count digits) but this is how I would write it in practice unless it actually needed to be high performance.
>>
>>55524010
It's not a fucking program, friend.
>>
>>55524031
wut?
>>
>>55524079
It's one line of code, not a program.
>>
>>55523969
isIn :: [Char] -> Char -> Bool
isIn [] _ = False
isIn (x:xs) ch = if x == ch then True else (isIn xs ch)

amount :: [Char] -> Integer
amount [] = 0
amount (x:xs) | isIn numbers x == True = 1 + amount xs
| isIn numbers x == False = 0 + amount xs
Where numbers = "0123456789"

main = do
input <- getLine
numbersInInput = amount input
print numbersInInput

So now it should work
>>
>>55524112
haskell?
>>
>>55524123
Yes
>>
>>55524128
could you recommend me a book or something, would really like to learn it
>>
>>55524112
Why are you writing isIn when elem already exists in Prelude? You could also just use the isDigit function in Data.Char and not reinvent the wheel?
>>
>>55514196
Returns a string u gon get stabbed
>>
File: 1462593304787.jpg (438KB, 900x2134px) Image search: [Google]
1462593304787.jpg
438KB, 900x2134px
>>55524145
To be honest, i never read a book about it so i dont know.
For me it was mostly trial and error(and with that i mean a shitload of trial and error) guided by api documentation and my functional programming professor.

But i think there are /g/ recommended ones, so they cant be that bad.
>>
>>55524105
More than half the solutions here are just code or a method. If you really want to, surround it or the others with a program startup and integer prompt. I just wanted to remain language agnostic (unless your language doesn't have the ternary operator, but then you are working in a shit language anyways)

Fucking birds with knives are never happy
>>
>>55524190
Because i am on mobile and so cant browse the api to look for what i need when also writing the code and its only 2 lines of code, so who cares.
>>
>>55524303
import Data.Char
main = print =<< fmap (length . filter isDigit) getLine

Here's a non-gay version of what you wrote
>>
>>55524299
Not an argument.

Write a program next time.

*stabs you, while not caring AT ALL*
>>
>>55513621
<script>
</html>

function WRITEAPROGRAMTHATDETERMINESTHENUMBEROFDIGITSOFANARBITRARYINPUTINTEGER(){
return 69
}{"_)}

</body>
>>
arbitrary input integer is too easy, i'll do it for an arbitrary

inputNumber <- abs(inputNumber)
output <- 0
if (inputNumber >= 1) {
output <- output + ceiling(log10(abs(inputNumber)))
}
decimalSplit <- strsplit(as.character(inputNumber),".",fixed=TRUE)[[1]]
if (length(decimalSplit) == 2) {
newSplit <- strsplit(decimalSplit[2],"")
output <- output + length(newSplit)
}
print(output)
>>
>>55525100
woops, forgot to add "arbitrary real"
>>
>>55525111
>>55525100
in retrospect i didn't account for user input of 0 and it will count the "0." portion of a decimal between 0 and 1 as one additional digit (which depending on desired usage might be appropriate)
>>
Why hello, stupid, where have you been?

int number_of_numbers(int input)
{
int output=0;
while(input)
{
input=(int)(input/10.0f);
output++;
}
return output;
}
>>
>>55513875
As a bird owner this makes me sad. It obviously was raised by humans and that smoke will hurt its lungs.
>>
>>55525376
the cigarette isn't lit and neither is the lighter

it was almost certainly staged and the bird didn't actually smoke
>>
Requesting Brainfuck solution
>>
>>
>>55526532
almost done
>>
>>55513621
print(len(input))


...I don't know what you were expecting.
>>
>>55527185
doesn't work you tard
>>
>>55513621
>>55526532
>>55527109
++++++++++[>+++++++>++++++++++>+++++++++++>+++<<<<-]>-.>>.++++++.<+.>--.>++.<<----.>>.<----.+++++++.--------.<+.+++.>+++++.<<-----------.[-]>[-]>[-]>[-]<<<,[>,]<[<]
>[[-]+[>]>+<<-[<-]>]++++++++[>++++++<-]++++++++++.>.<<++++++++++[<+++<++++++++++>>-]<++.<.+++++.--.++.+++++++++++.-.

You go birdo
>>
>>55527195
not him but it would kind of maybe work if you cast it as a string first, although you'd have to subtract 1 to get rid of the decimal point
>>
>>55527226
if input is a string type instead of int he already failed
>>
>>55527226
It's already a string if you're asking the user for input. I missed a pair of brackets.

print(len(input()))


>12345
5
>321
3
>>
>>55527212
do you write this manually or do you translate it from something else
>>
>>55527261
Depends on the language, but usually inputs are always strings, then you try to cast to whatever type you're expecting and handle from there.
>>
>>55527269
Manually. Unfortunately I just realised I'm an idiot and it only works for number from 1 to 9 digits :/
>>
Wrote this on my phone, have not tested. I pray for the knifebird to forgive me!

class Number
{
constructor(value)
{
this.value = value;
}

get digits()
{
return this.value.toString().length;
}
}

// Example:
let num = new Number(10);
console.log(num.digits);
>>
File: Bird2.gif (682KB, 480x270px) Image search: [Google]
Bird2.gif
682KB, 480x270px
>>55517464
Sorry, I have the important x86 system calls memorized so I just use those. Have this bird as compensation
>>
>>55526080
There is longer one showing them lighting it.
>>
>>55527266
yeah but you're supposed to use an int type, so you'd have to do
 int(input()) 
, when you now try to use
 len() 
it will fail
>>
>>55513621
length . show

Or
ceiling . logBase 10 . succ

I think
>>
>>55527266
000056
>>
>>55527491
>>> print(len(input()))
00056
5


>>55527378
Why would I do that? If you really want to:

print(len(str(int(input()))))


Converting to string and counting the number of characters is the easiest way to do it.
>>
>>55527592
000056, as an integer, should have two digits. Integers do not have leading zeroes. You're just printing string length, nonspecific to any kind of number, let alone integers.
>>
File: Screenshot_20160711_235518.png (64KB, 1069x628px) Image search: [Google]
Screenshot_20160711_235518.png
64KB, 1069x628px
cat main.tsc
>>
>>55513621
def digits(num):
return len(str(num))
>>
>>55514178
Probably because of the game EVE Online
>>
>>55515999
>>55517281
>being this pedantic/autistic
>>
>>55513621
You know, the novelty and urgency of a bird wanting to stab me really wears off when it's perpetually on going.
>>
function phpbait($num) {
if(is_numeric($num) {
$length = strlen(trim($num));
echo 'The number has {$length} digits' ;
} else {
echo 'not a number' ;
exit();
}
}
>>
>>55527185
>-25
3
>>
print(len(string(input())))
>>
>>55518174
main = do
in <- getLine
let iin = read in :: Integer
print $ length $ show $ abs iin
>>
>>55513621
Strategies:
- Format to string, get length.
- Cast to float, floor(log10(x)) +1
- 19 < Log10(2^64) < 20, so the largest 64-bit integer has at most 20 digits. Precompute a table of 19 powers of ten, binary or linear search against your number to determine the number of digits.
- Repeatedly multiply a counter by 10, comparing to your number. (Like linear search above, except without precomputation).

Any other ideas?
>>
>>55513621
def count_digits(num):
return len(str(num))
>>
QUICK
fuck off and do your own homework
>>
Batch is my favorite language
How to do this in batch?
>>
>>55530447
Without benchmarking, I'd guess linear search + precomputed powers of ten is fastest, followed by floating point cast, then multiplying a counter by 10 and comparing, then binary search on precomputed table, and finally string conversion.
>>
>>55530527
>doesn't know how to use his favourite language
>>
>>55530447
Add to that "divide by ten repeatedly and compare against 0".
>>
>>55513621
>WRITE A PROGRAM THAT DETERMINES THE NUMBER OF DIGITS OF AN ARBITRARY INPUT INTEGER

integer has bound at value 2147483647, 10 digits, and value 0, 1 digit. If it's negative just flip before starting, negative won't change the number of digits.

You only have to look at the most significant bit most of the time.

Bit shift integer left until its most significant bit is in the highest possible position (without overflow)

count the number of shifts you did, convert to number of digits with a precomputed table.

if ambiguous, check the next most significant bit.
>>
>>55530527
function countDigit
{
BASE=10
INT=%1
COUNT=1
if [[ $INT -lt 0 ]]
then
INT=$((0 - INT))
fi
while [[ $INT -ge $BASE ]]
do
INT=$((INT / BASE))
COUNT=$((COUNT + 1))
done
echo $COUNT
}
>>
>>55530672
>INT=%1
Should have been INT=$1
>>
>>55530631
Shifts are base 2, and you are trying to count base 10 digits.

You could store a list of shifts / digit, I guess, since no shift will pass 2 base 10 digits, but you'll never be able to say for sure by just doing shifts. If you find the number hits 0 between 64 and 128, you only know it is either 2 or 3 digits in base 10.
>>
>>55530672
>>55530696
I'm looking for Batch not Bash
>>
>>55530755
>Shifts are base 2, and you are trying to count base 10 digits.
hence "count the number of shifts you did, convert to number of digits with a precomputed table." and "
if ambiguous, check the next most significant bit."
>>
>>55530762
What the fuck is batch?
>>
>>55530774
Sorry, I was being an idiot. Realized you'd explained fully after posting.

I bet linear search against table of powers of ten is faster than counting shifts then doing a single lookup, though.

It'd be fun to benchmark a bunch of these variations. I'm sure someone has already, but I think I'll give it a shot when I get home.
>>
>>55530803
From wikipedia
Abatch fileis a kind of script file in DOS,OS/2 and Windows. It consists of a series of commands to be executed by the command line interpreter, stored in a plain text file. A batch file may contain any command the interpreter accepts interactively and use constructs that enable conditional branching and looping within the batch file, such as "if", "for", "goto" and labels. The term "batch" is from batch processing, meaning "non-interactive execution", though a batch file may not process abatchof multiple data.
>>
>>55530826
>I bet linear search against table of powers of ten is faster than counting shifts then doing a single lookup, though.

Yeah I probably agree. though with the caveat that: on many systems, checking a single bit for its parity is much faster than performing an integer comparison. Shifts are of course very fast as well.

Here's the big issue though:
if you build all these solutions and try to benchmark them, one will win because of serendipitous cache and pipeline efficiency, not algorithmic elegance. In which case the performance will vary with the length of your integer, which is dumb. You could even take the OP's use of "arbitrary" to mean the integer could be larger or smaller than a machine integer, in which case comparisons would take longer after certain size thresholds (but single-bit checks would not)

Love computer science, fuck computer engineering.
>>
>>55530903
>>55530826
could you guys shut the fuck up?

you're trying to find the number of digits in a numerical value. this is done by recursive division. the end. Any other method is trying to make something that is not mathematical into something mathematical. Pure maths do not make sense of bases used to output numbers in digit sequences.

Also fuck all those coding camp pajeets who convert the number to a string. The function that converts your integer into a string already cycles through every digit by dividing the integer then does a bunch of shit to make it into a character array. You're wasting a lot of cpu cycles by being lazy.
>>
>>55531082
>you're trying to find the number of digits in a numerical value. this is done by recursive division. the end.
yes and multiplication is just repeated addition and exponentiation is just repeated multiplication....oh wait, that hasn't been true since the 60s
>>
#include <cmath>

int main()
{
int num;
std::cin >> num;
std::cout << (num != 0 ? std::log(std::abs(num)) + 1 : 1) << std::endl;
}
>>
>>55521568
that doesn't work though. you can't use `#` and substitution in the same parameter expansion.
>>
>>55530853
You are making me work in a literal nigger language senpai.

This is a first shot. I don't know if it will work. This fucked ass language opens so many doors to syntax errors.
@echo off
set BASE=10
set INT="%1"
set COUNT=1

IF /I "%INT%" LSS 0 set /A INT=0-%INT% >nul

:WHILE1 IF /I "%INT%" GEQ "%BASE%"
set /A INT=%INT%/%BASE% >nul
set /A COUNT=%COUNT%+1 >nul
GOTO :WHILE1

echo %COUNT%
>>
>>55531291
the horror!

>>55513845
pretty
>>
>>55531291
>>55530853
Well shit. I managed to make it work.

@echo off
set BASE=10
set INT=%1
set COUNT=1

echo Base: %BASE%
echo Int: %INT%
echo Count: %COUNT%

IF /I %INT% LSS 0 set /A INT=0-%INT%

:1
IF /I %INT% GEQ %BASE% (
set /A INT=%INT%/%BASE%
set /A COUNT=%COUNT%+1

echo Base: %BASE%
echo Int: %INT%
echo Count: %COUNT%

GOTO :1
)

echo %COUNT%


I hope I never have to use batch again. It threw an RTE because I had the opening parenthesis for my IF statement on its own line.
>>
>>55531448
oops, left the debug shit in there
@echo off
set BASE=10
set INT=%1
set COUNT=1

IF /I %INT% LSS 0 set /A INT=0-%INT%

:1
IF /I %INT% GEQ %BASE% (
set /A INT=%INT%/%BASE%
set /A COUNT=%COUNT%+1
GOTO :1
)

echo %COUNT%
>>
Python 3 fag:

n = int(input("Enter an integer: "))
digit_count = 0
while n > 0:
n //= 10
digit_count += 1
print("Number of digits: {}".format(digit_count))
>>
>>55530672
Hah, I wrote that on my cellphone and after replacing %1 with $1 it succeded on the first try.
>>
File: 1353131529030.jpg (106KB, 640x430px) Image search: [Google]
1353131529030.jpg
106KB, 640x430px
>>55517511
>tfw .length is a function you have to call explicitly
>>
>>55531567
How do lower level languages store/manage/report the length of their arrays?
>>
>>55531583
i'm just fuckin with ya, I actually get spooked by languages with getters that can have side effects
>>
Inside Run event handler (console application)

  Print("Enter an integer value, or don't, I don't really give a fuck: ")
dim s as string = input
dim intLength as integer = Len(s)
dim sh as new shell
Print("It is " + intLength.ToText + " digits or characters long, faggot." + Chr(13) + Chr(13) )
Print("Press enter to close program...")
sh.Execute("pause")


I am the only Xojo user on /g/

Proceed to make fun of me
>>
>>55531625
It doesn't matter that you're using Xojo. You took the string length way. That's pajeet as fuck and it misses the point of the question completely.
>>
>>55531645

Why would I do more work than I have to if I can just count the digits easier this way?

Just count the length. This doesn't even require your math shenanigans.
>>
>>55531683
Okay, firstly, the problem is to count the digits in an integer, not a string. That the input passed if of integer type is implied.

Secondly, if you just take a string and count its characters, you're not taking in account non-numerical input, negative numbers, non-integer numbers, whitespace, etc. Your answer is only right if the user provides the right input.
>>
File: fg.jpg (40KB, 630x420px) Image search: [Google]
fg.jpg
40KB, 630x420px
>>55531730

>Secondly, if you just take a string and count its characters, you're not taking in account non-numerical input, negative numbers, non-integer numbers, whitespace, etc.

Oh ok sorry

I just did what OP told me to do. I guess if your end users are intentionally trying to break it, they would.

I guess I could do math times and for loops to do it correctly but I am going to bed /g/uy
>>
>>55514291

Any reasonable log_b implementation is implemented in terms of a lookup table and some additions / subtractions, so the log10 will be faster.
>>
>>55513621
Wow that was stupid easy.

int digits(const int n)
{
return log10(n) + 1;
}
>>
>>55531730

I know I am still 'doing it wrong' because not using lolmath and this is incredibly innefficient compared to everyone else, but I defeated your challenge nonetheless!!

  dim s as string = " "
dim boolNumericInputCheck as boolean = False
dim intNumericStringValue as integer = 0

while boolNumericInputCheck = False or intNumericStringValue <= 0
Print("Enter an integer value that is more than 0: ")
s = StdIn.ReadLine
boolNumericInputCheck = IsNumeric(s)

If boolNumericInputCheck = True Then
intNumericStringValue= Val(s)
Else
intNumericStringValue = 0
End if

Wend

dim count as integer = Len(s)


dim sh as new shell
Print("It is " + count.ToText + " digits long." + Chr(13) + Chr(13) )
Print("Press enter to close program...")
sh.Execute("pause")
>>
>>55532024
>opening brace on a new line
You're still getting stabbed, just by me instead of the bird
>>
>>55532024
No wait.
Zero is still 1 digit right?

int digits(int n)
{
if (!n)
return 1;
else
return log10(abs(n)) + 1;
}
>>
File: kk.jpg (38KB, 192x279px) Image search: [Google]
kk.jpg
38KB, 192x279px
>>55532099

O-Oh man, decimal points fuck it up.

I would spend time fixing that logic, but I am really going to bed now.

Sorry I am bad at programming /g/ - I still love it even though everything I make is horribly, horribly inefficient!

... I think that's why I like it though :D
>>
>>55532134
return n ? log10(abs(n)) + 1 : 1;
>>
>>55532165
OP asked for integers tho.
>>
>>55521886
doesn't work, but
print(len(input("type a number... ")))

does

why do people hate on python? it seems easy/functional
>>
>>55515337
But you clearly did input 9 digits, even if it simplifies to 2. The OP didn't put that in his specification, so fuck him. He can pay me another $40 to write a fix.

perl -le '$_=<>; chomp; s/[^\d]//g; print length'
>>
Beat this niggers
int count_ifs (int n) {
//maximum size of an int is 10
if (n < 0) return false;
if (n < 10) return 1;
if (n < 100) return 2;
if (n < 1000) return 3;
if (n < 10000) return 4;
if (n < 100000) return 5;
if (n < 1000000) return 6;
if (n < 10000000) return 7;
if (n < 100000000) return 8;
if (n < 1000000000) return 9;
if (n < 10000000000) return 10;
return 11;
}
>>
>>55532442
>
//maximum size of an int is 10

I'm not entirely sure this is true
>>
>>55532878
The largest u64 is 20 digits.
>>
File: bar.png (9KB, 520x150px) Image search: [Google]
bar.png
9KB, 520x150px
Solution in Piet. Accepts 2 ints from stdin: the number and its radix.
>>
File: flygt.webm (1MB, 480x262px) Image search: [Google]
flygt.webm
1MB, 480x262px
Cooler Program
Thread posts: 321
Thread images: 26


[Boards: 3 / a / aco / adv / an / asp / b / bant / biz / c / can / cgl / ck / cm / co / cock / d / diy / e / fa / fap / fit / fitlit / g / gd / gif / h / hc / his / hm / hr / i / ic / int / jp / k / lgbt / lit / m / mlp / mlpol / mo / mtv / mu / n / news / o / out / outsoc / p / po / pol / qa / qst / r / r9k / s / s4s / sci / soc / sp / spa / t / tg / toy / trash / trv / tv / u / v / vg / vint / vip / vp / vr / w / wg / wsg / wsr / x / y] [Search | Top | Home]

I'm aware that Imgur.com will stop allowing adult images since 15th of May. I'm taking actions to backup as much data as possible.
Read more on this topic here - https://archived.moe/talk/thread/1694/


If you need a post removed click on it's [Report] button and follow the instruction.
DMCA Content Takedown via dmca.com
All images are hosted on imgur.com.
If you like this website please support us by donating with Bitcoins at 16mKtbZiwW52BLkibtCr8jUg2KVUMTxVQ5
All trademarks and copyrights on this page are owned by their respective parties.
Images uploaded are the responsibility of the Poster. Comments are owned by the Poster.
This is a 4chan archive - all of the content originated from that site.
This means that RandomArchive shows their content, archived.
If you need information for a Poster - contact them.