[Boards: 3 / a / aco / adv / an / asp / b / biz / c / cgl / ck / cm / co / d / diy / e / fa / fit / g / gd / gif / h / hc / his / hm / hr / i / ic / int / jp / k / lgbt / lit / m / mlp / mu / n / news / o / out / p / po / pol / qa / r / r9k / s / s4s / sci / soc / sp / t / tg / toy / trash / trv / tv / u / v / vg / vp / vr / w / wg / wsg / wsr / x / y ] [Home]
4chanarchives logo
QUICK IN YOUR FAVORITE PROGRAMMING LANGUAGE, WRITE A PROGRAM
Images are sometimes not shown due to bandwidth/network limitations. Refreshing the page usually helps.

You are currently reading a thread in /g/ - Technology

Thread replies: 255
Thread images: 26
File: 1467471847306.jpg (29 KB, 412x430) Image search: [Google]
1467471847306.jpg
29 KB, 412x430
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 (118 KB, 853x600) Image search: [Google]
1467005968508.jpg
118 KB, 853x600
>>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 (811 KB, 1069x1081) Image search: [Google]
1468103944456.png
811 KB, 1069x1081
>>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 (260 KB, 458x360) Image search: [Google]
image.png
260 KB, 458x360
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 (15 KB, 480x360) Image search: [Google]
ross-perot.jpg
15 KB, 480x360
>>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 (430 KB, 1600x900) Image search: [Google]
wall_e_eve-1600x900.jpg
430 KB, 1600x900
>>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 (52 KB, 233x233) Image search: [Google]
1449551937430.jpg
52 KB, 233x233
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 (29 KB, 724x211) Image search: [Google]
absolutetruth.jpg
29 KB, 724x211
>>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 (2 MB, 300x173) Image search: [Google]
bird stealing knife.gif
2 MB, 300x173
>>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 (17 KB, 480x352) Image search: [Google]
1462411508798.jpg
17 KB, 480x352
>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 (4 KB, 557x148) Image search: [Google]
staaaaab!.png
4 KB, 557x148
>>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 (1 KB, 342x76) Image search: [Google]
yousuck.png
1 KB, 342x76
>>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 (7 KB, 274x78) Image search: [Google]
Cshaper.jpg
7 KB, 274x78
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 (50 KB, 780x369) Image search: [Google]
Cshapest.jpg
50 KB, 780x369
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 (2 MB, 640x352) Image search: [Google]
1443526747771.gif
2 MB, 640x352
>>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 (24 KB, 944x278) Image search: [Google]
eOK8CCZ.png
24 KB, 944x278
>>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 (438 KB, 900x2134) Image search: [Google]
1462593304787.jpg
438 KB, 900x2134
>>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 (682 KB, 480x270) Image search: [Google]
Bird2.gif
682 KB, 480x270
>>55517464
Sorry, I have the important x86 system calls memorized so I just use those. Have this bird as compensation
Thread replies: 255
Thread images: 26

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

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.
If a post contains personal/copyrighted/illegal content you can contact me at [email protected] with that post and thread number and it will be removed as soon as possible.
DMCA Content Takedown via dmca.com
All images are hosted on imgur.com, send takedown notices to them.
This is a 4chan archive - all of the content originated from them. If you need IP information for a Poster - you need to contact them. This website shows only archived content.