title: Is it an Odd Word?

text:
# Question
Title: Is it an Odd Word?
## Challenge

Given a single word as input, determine if the word is odd or even.

## Odd and Even words

Assume the general rules:

```
odd + odd = even
even + odd = odd
odd + even = odd
even + even = even

```

In the alphabet, the odd letters are:

```
aeiou

```

And the even letters are:

```
bcdfghjklmnpqrstvwxyz

```

The same applies to capital letters (`AEIOU` are odd and `BCDFGHJKLMNPQRSTVWXYZ` are even).

You then 'add' each of the letters in the word together. For example, the word `cats` is equivalent to:

```
even + odd + even + even

```

Which simplifies to:

```
odd + even

```

Which simplifies further to:

```
odd

```

So the word `cats` is odd.

## Examples

```
Input:  trees
Output: even

```

---

```
Input:  brush
Output: odd

```

---

```
Input:  CAts
Output: odd

```

---

```
Input:  Savoie
Output: even

```

---

```
Input:  rhythm
Output: even

```

## Rules

All input will be a single word which will only contain alphabetical characters.

If the word is odd, output a truthy value. If the word is even, output a falsey value.

## Winning

The shortest code in bytes wins.

# Answer
# 05AB1E, 6 bytes

```
lžMÃgÉ

```

**Explanation**

```
l       # convert to lower case
 žMÃg   # count odd letters
     É  # true if odd else false

```

Try it online!
> 7 votes

# Answer
# EXCEL, 79 bytes:

```
=MOD(SUMPRODUCT(LEN(A1)-LEN(SUBSTITUTE(LOWER(A1),{"a","e","i","o","u"},""))),2)

```

**input:**
This function can be placed anywhere **EXCEPT A1**
Put your word in question into A1.

Output: 0 if even, 1 if odd.
> 18 votes

# Answer
## JavaScript (ES6), ~~34~~ ~~41~~ ~~33~~ 32 bytes

Saved 1 bytes thanks to Arnauld:

```
s=>~s.split(/[aeiou]/i).length&1

```
* Odd word : returns `1`
* Even words : returns `0`

---

Previous solutions:

33 bytes thanks to Arnauld:

```
s=>s.split(/[aeiou]/i).length&1^1

```
* Odd word : returns `1`
* Even words : returns `0`

Another way without bitwise operators:

```
s=>++s.split(/[aeiou]/i).length%2

```

41 bytes:

```
(s,a=s.match(/[aeiou]/ig))=>a&&a.length%2

```
* Odd word : returns `1`
* Even words with odd letters : returns `0`
* Even words with no odd letters : returns `null`

42 bytes to return `0` instead of `null`:

```
(s,a=s.match(/[aeiou]/ig))=>a?a.length%2:0

```

34 bytes, breaks on words with no odd letters:

```
f=s=>s.match(/[aeiou]/ig).length%2

```

Saved 2 bytes thanks to Shaun H

```
s=>s.match(/[aeiou]/ig).length%2

```
> 14 votes

# Answer
# C, 42 bytes

```
f(char*s){return*s&&2130466>>*s&1^f(s+1);}

```

This works with GCC 4.x on a x86-64 CPU. Results may vary with different setups.

Test it on repl.it.

At the cost of 5 more bytes, undefined behavior can be avoided, so the code should work as long as *int*s are at least 32 bits wide.

```
f(char*s){return*s&&2130466>>(*s&31)&1^f(s+1);}

```

### How it works

Modulo **32**, the character codes of all odd letters are **1**, **5**, **9**, **15**, and **21**. **2130466** is the 32-bit integer that has set bits at these positions and unset bits at all others.

When **f** is called on a string, it first checks if the first character of the string is a null byte (string terminator). If it is, `*s` yields **0** and **f** returns **0**. Otherwise, `*s` yield the character code of a letter and the right argument of the logical AND (`&&`) is executed.

For `>>`, GCC generates a shift instruction. On a x86-64 CPU, the corresponding instruction for a 32-bit integer ignores all but the lower 5 bits of the right argument, which avoids reducing `*s` modulo **32**. The right shift and the following bitwise AND with **1** extracts the bit of **2130466** that corresponds to the letter, which will be **1** if and only if the letter is odd.

Afterwards, we increment the pointer **s** (effectively discarding the first letter), call **f** recursively on the beheaded string, and take the bitwise XOR of the result from above and the result of the recursive call.
> 9 votes

# Answer
# sed 44 (42 + 1 for -n) 43

-1 thanks to Neil

```
s/[aeiou][^aeiou]*[aeiou]//gi
/[aeiou]/Ico

```

Prints `o` for odd and nothing for even
> 8 votes

# Answer
# Brain-Flak ~~206~~ ~~196~~ ~~192~~ 178 + 3 = 181 bytes

Try it Online!

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

```

This requires the `-c` flag to run in ASCII mode adding an extra 3 bytes to the length of the program.

## Ungolfed

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

```

## Explanation

First store the stack height for future purposes

```
([]<...>

```

Then while the stack is not empty (assumes that none of the characters is zero)

```
{...}

```

Subtract ninety seven (and store 3 for later optimizations)

```
({}[((((((()()())){}){}){}){}){}()])

```

If it is not zero (i.e. not a)

```
{...}

```

Subtract 4 (and store 4 for later optimizations)

```
({}[({}())])

```

If it is not zero (i.e. not e)

```
{...}

```

Subtract 4 (and store 4 for later optimizations)

```
({}[({})])

```

If it is not zero (i.e. not i)

```
{...}

```

Subtract 6 (and store 6 for later optimizations)

```
({}[({}()())])

```

If it is not zero (i.e. not o)

```
{...}

```

Subtract 6 (store 6 because the program expects one later)

```
({}[({})])

```

If it is not zero (i.e. not u)

```
{...}

```

Move the remainder to the other stack and put a zero on the active stack to escape all of the ifs

```
({}<>)(<>)

```

Once all of the ifs have been escaped remove the zero and the six

```
{}{}

```

Once all the characters have been processed subtract the height of the offset from the originally stored height.

```
...<>[[]]<>)

```

Mod by two

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

```
> 8 votes

# Answer
## Python, 41 bytes

```
lambda s:sum(map(s.count,"aeiouAEIOU"))%2

```
> 8 votes

# Answer
# Jelly, ~~13 12~~ 11 bytes

-1 byte thanks to @Luis Mendo (use  to replace `%2`)
-1 byte thanks to @Dennis (use a string compression)

```
Œlf“¡ẎṢɱ»LḂ

```

All test cases are at **TryItOnline**

How?

```
Œlf“¡ẎṢɱ»LḂ - Main link takes an argument - s
Œl          - lowercase(s)
   “¡ẎṢɱ»   - string of lowercase vowels (compression using the words a and eoui)
  f         - filter - keep only the vowels
         L  - length - the number of vowels
          Ḃ - Bit (modulo 2)

```

---

**Non-competing, 5 bytes** (since I just added the function `Øc`)

```
fØcLḂ

```

Test cases also at **TryItOnline**

Same as above, but `Øc` yields the Latin alphabet's vowels, `'AEIOUaeiou'`
> 7 votes

# Answer
# Brain-Flak, ~~524, 446~~, 422 bytes

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

```

Try it online!

Ungolfed, more readable version:

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

```
> 7 votes

# Answer
# Haskell, ~~38~~ 37 bytes

```
odd.length.filter(`elem`"aeiouAEIOU")

```

Thanks to Angs for one byte!
> 6 votes

# Answer
# Python, 42 bytes

```
lambda s:sum(c in"aeiouAEIOU"for c in s)%2

```

Not a whole lot to explain here. An unnamed function that returns 0 or 1.
> 6 votes

# Answer
# Python 3, 53 Bytes

This can probably be golfed further:

```
lambda n:[x in 'aeiou' for x in n.lower()].count(1)&1

```
> 4 votes

# Answer
**C 52 bytes**

```
h(o){o=strpbrk(o,"aeiouAEIOU");return o?1^h(o+1):0;}

```

the main and the result:

```
main()
{int   k;
 char *a[]={"trees","brush","CAts","Savoie","rhythm", 0};

 for(k=0;a[k];++k)
     printf("[%s]=%s\n", a[k], h(a[k])?"odd":"even");
}

/*
91
[trees]=even
[brush]=odd
[CAts]=odd
[Savoie]=even
[rhythm]=even

*/

```
> 4 votes

# Answer
# Pyth, 14 bytes

```
%l@"aeiou"rQ02

```

Try it Online!

Explanation:

```
  @"aeiou"       Grab only the vowels
          rQ0      From lowercased input
 l                 Get the length of this
%            2     And mod 2 to check for oddness

```
> 3 votes

# Answer
# Ruby, 30 bytes

```
->w{w.scan(/[aeiou]/i).size%2}

```
> 3 votes

# Answer
# Vim, ~~32, 31~~, 29 keystrokes

```
:s/[^aeiou]//gi
C<C-r>=len(@")%2<cr>

```

Since the V interpreter is backwards compatible, you can try it online! right here.

*~~One~~ Three bytes saved thanks to m-chrzan!*
> 3 votes

# Answer
**Java, 73**

```
boolean f(String s){return s.replaceAll("(?i)[^aeiou]","").length()%2>0;}

```

saw a couple other java answers, otherwise wouldn't have shared. Thanks to Phaeze for saving a byte.
> 3 votes

# Answer
# dimwit, 14 bytes (non-competing)

```
ar[aeiou]}et}T

```

I thought this would be a fun, simple challenge to start with for a new language.

### Explanation

* `a` \- push a new array to the matrix
* `r[aeiou]}` \- count occurrences of all values matching the regex "\[aeiou\]" in the first array (since the first array contains the input), ignoring case, and push that value to the end of the last array.
* `e` \- if the last number in the last array is even (which we set to the number of occurrences), perform the next operations up until a closing bracket ("}")
* `t` \- stop execution, clear the matrix, and set the first value to be false
* `}` \- end of `e` code block
* `T` \- stop execution, clear the matrix, and set the first value to be true

### Try it online!

Use the Input field to enter the word.

I'll soon add documentation...
> 3 votes

# Answer
# Bash, 36 bytes

```
x=${1,,//[aeiou]/}
((1&${#1}&${#x}))

```

Try it online!

# Zsh, 30 bytes

```
((1&$#1&${#${1:l}//[aeiou]/}))

```

Try it online!

Accepts input as its first argument. Exits with nonzero if even, exits zero if odd.

We *barely* beat out the bash+coreutils solution!

```
x=${1,,//[aeiou]/}  # lowercase first argument, then remove all [aeiou]
((1&${#1}&${#x}))
  1&     &          # bitwise-and 1 with
    ${#1} ${#x}     # length of first parameter and length of stripped parameter
((             ))   # if nonzero, exit 0 (truthy in shell)

```

The Zsh solution is very similar, but uses the ability to nest parameter expansions to save an assignment.
> 3 votes

# Answer
# K (ngn/k), 13 bytes

```
=/^"aeiou"?_:

```

Try it online!

Returns `1` for "even" inputs and `0` for "odd" ones.

* `_:` lowercase the (implicit) input
* `^"aeiou"?` generate a bitmask indicating which characters in the (lowercased) input are *not* vowels
* `=/` do an equals-reduce; if there are an even number of `0`s (i.e. vowels), this returns `1`. if there are an odd number, it returns `0`
> 3 votes

# Answer
## Retina, 19 bytes

```
Mi`[aeiou]
[13579]$

```

Try it online! (The first line enables a linefeed-separated test suite.)

The first line counts the vowels in the input. The second line checks that the result is odd.
> 2 votes

# Answer
## PowerShell v2+, ~~45~~ 42 bytes

```
($args[0]-replace'[^aeiouAEIOU]').Length%2

```

Takes input `$args[0]`, sends it through `-replace` to remove all non-vowel characters, takes the resulting `.length`, and `%2` to check whether it's odd/even.

### Examples

```
PS C:\Tools\Scripts\golfing> 'trees','brush','CAts','Savoie','rhythm'|%{"$_ --> "+(.\is-it-an-odd-word.ps1 $_)}
trees --> 0
brush --> 1
CAts --> 1
Savoie --> 0
rhythm --> 0

```
> 2 votes

# Answer
# Octave, 34 bytes

```
@(s)mod(nnz(~(s'-'aeiouAEIOU')),2)

s'-'aeiouAEIOU'    % Creates a 2D-matrix where each of the odd letters are
                   % subtracted from the string s
~(s'-'aeiouAEIOU') % Negates that array, so the all zero elements become 1
nnz( .... )        % Counts all the non-zero elements (the odd letters)
mod(nnz( ....),2   % Takes this sum modulus 2

```

This is 6 bytes shorter than the traditional approach using `ismember`, `@(s)mod(sum(ismember(s,'aeiouAEIOU')),2)`, and two bytes shorter than the regex approach: `@(s)mod(nnz(regexpi(s,'[aeiou]')),2)`.

Test it here.
> 2 votes

# Answer
# Java 7, 88

```
boolean f(char[]s){int x=0;for(char c:s)if("aeiouAEIOU".indexOf(c)>=0)++x;return x%2>0;}

```

Ungolfed:

```
  boolean f(char[] s) {
    int x = 0;
    for (char c : s) {
      if ("aeiouAEIOU".indexOf(c) >= 0) {
        ++x;
      }
    }
    return x % 2 > 0;
  }

```
> 2 votes

# Answer
# J, 20 bytes

```
2|+/@e.&'aeiouAEOIU'

```

Straight-forward approach

## Explanation

```
2|+/@e.&'aeiouAEOIU'  Input: string S
     e.&'aeiouAEOIU'  Test each char in S for membership in 'aeiouAEOIU'
  +/@                 Sum those values
2|                    Take it modulo 2 and return

```
> 2 votes

# Answer
# C# ~~64~~ ~~62~~ ~~56~~ 50 Bytes

```
s=>1>s.Split("aeiouAEIOU".ToCharArray()).Length%2;

```
* ~~We are already using linq, so Contains saves 2 bytes over IndexOf~~
* ~~Using the method overload of Count saves 6 bytes~~
* Thanks to @Milk for suggesting a neat method and saving 6 more bytes

An anonymous function that takes a string and counts the odd letters then returns true if there is an odd number of them or false if there is not.

This new solution splits the string on any of the characters in the given char array. The mechanics of this flip the meaning of the `%2` result; 0 is now odd and 1 even hence the `1>`.

Try it online here!
> 2 votes

# Answer
# Japt, 7 bytes

```
1&Uè"%v

```

**Test it online!** Outputs 1 for odd, 0 for even.

### How it works

```
         // Implicit: U = input string
  Uè     // Count the number of matches of the following regex in the input:
    "%v  //   /[AEIOUaeiou]/g
1&       // Take only the first bit (convert 1, 3, 5, etc. to 1, and others to 0)
         // Implicit output

```
> 2 votes

# Answer
# PHP, 41 bytes

```
<?=count(spliti("[aeiou]",$argv[1]))%2-1;

```

This outputs -1 for truthy and 0 for falsey.
> 2 votes

# Answer
## Mathematica, 44 bytes

```
OddQ@StringCount[#,Characters@"aeiouAEIOU"]&

```

Gives True for an odd string and False for an even one.
> 2 votes

# Answer
# q, 29 bytes

```
{mod[sum x in "aeiouAEIOU";2]}

```
> 2 votes

# Answer
# Japt v2.0a0, 5 bytes

Outputs `1` for odd and `0` for even.

```
è\v u

```

Try it (Includes all test cases)

```
è\v u     :Implicit input of string
è         :Count the occurrences of
 \v       :  RegEx /[aeiou]/gi
    u     :Modulo 2

```
> 2 votes

# Answer
# Brachylog, ~~11~~ 9 bytes

```
ḷ{∈Ṿ}ˢḍz₂

```

Try it online!

The predicate fails if the input is odd and succeeds if it is even.

```
ḷ{  }ˢ       For each lowercased letter of the input,
   Ṿ         map it to the string of lowercase vowels
  ∈          if it's an element of it
     ˢ       and delete it otherwise.
      ḍ      Split the list in half.
       z₂    Are the halves the same length?

```
> 2 votes

# Answer
# Java (JDK), ~~53~~ ~~52~~ ~~51~~ 42 bytes

```
s->(s+"#").split("(?i)[AEIOU]").length%2<1

```

Try it online!

Edit: Saved ~~a byte~~ 2 bytes thanks to @JonathanFrech
Edit: Saved another 9 bytes thanks to @Deadcode
> 2 votes

# Answer
# Vyxal, 3 bytes

```
A∑∷

```

Try it Online!
> 2 votes

# Answer
# C# 36 Bytes

```
s=>s.Count("aeiouAEIOU".Contains)%2;

```

Returns 1 for odd, 0 for even.

Try it online here!
> 2 votes

# Answer
# MATL, ~~8~~, 7 bytes

```
13Y2mso

```

Try it online!

Explanation:

```
13Y2    % Push the string 'aeiouAEIOU', a predefined literal.
    m   % For each char of the input that is in that string, push a one. For every other element, push a zero.
     s  % Sum this array
      o % Mod 2

```
> 1 votes

# Answer
## Pyke, 10 bytes

```
l1~Vm/s 2%

```

Try it here!
> 1 votes

# Answer
# Actually, 17 bytes

Golfing suggestions welcome. Try it online!

```
ù╝"aeiou"`╛c`MΣ1&

```

**Ungolfing**

```
                    Implicit input s.
ù╝                  Add s.lower() to register 1.
  "aeiou"`  `M      Push the string "aeiou" and map the following function over it.
          ╛         Push register 1 to stack.
           c        Count the occurrences of "a", then "e", etc.
              Σ     Sum the counts of these occurrences.
               1&   x&1 == x%2.
                    Implicit return.

```
> 1 votes

# Answer
# Perl, 18/19 bytes

Includes +1 for `-p`

Give input on STDIN, prints `0` for even, `1` for odd

```
#!/usr/bin/perl -p
$_=1&lc=~y;aeiou;

```

Must be put in a file, but the file must ***not*** have a final newline giving 18 bytes. This is admittedly abusing the perl counting rules a bit since this actually doesn't work when run in a `-e` commandline which implicitely adds a final `\n` which makes the program not work. So more honest but 19 bytes is:

```
#!/usr/bin/perl -p
$_=1&lc=~y;aeiou;;

```
> 1 votes

# Answer
# CJam, ~~18~~ 17 bytes

```
0lel"aeiou"f{&,^}

```

Try it online!

### Explanation

```
0                 e# Push 0
 l                e# Read line from input
  el              e# Convert to lowercase
   "aeiou"        e# Push this string
          f{   }  e# Map code block to each char of the input and the string "aeiou"
            &     e# Set intersection of each input char with the "aeiou". The result
                  e# is either that char or the empty string
             ,    e# Length. Gives 0 or 1
              ^   e# Binary XOR. Uses the initial 0 the first time
                  e# Implicitly display

```
> 1 votes

# Answer
## R, 164 bytes

I'm sure this can be done better, but it's still good practice.

```
f<-function(w){
l<-"aeiouAEIOU"
c<-0
for(i in 1:10){
for(j in 1:nchar(w)){
if(substr(l,i,i)==substr(w,j,j)){c<-c+1}}}
if(c%%2==0){print("F")}else{print("T")}}

```

## input/output

```
> f("trees")
[1] "F"
> f("brush")
[1] "T"
> f("CAts")
[1] "T"
> f("Savoie")
[1] "F"
> f("rhythm")
[1] "F"

```

"F" for false and "T" for true.
> 1 votes

# Answer
## Bash + coreutils, 37 bytes

```
bc<<<!`sed s:[^aeiou]::ig\;q|wc -m`%2

```

The input word is taken from STDIN. Output is 1 if the word is odd, or 0 if it is even.

**Explanation:**

```
       sed s:[^aeiou]::ig\;q     # remove even letters from input and exit sed
       |wc -m                    # count remaining chars (odd letters + 1 for \n)
bc<<<!`                     `%2  # apply mod 2 and invert the boolean result

```

**Run example:**

```
me@LCARS:/PPCG$ ./odd_word.sh
trees
0

```
> 1 votes

# Answer
# PHP, 43 Bytes

```
<?=preg_match_all("#[aeiou]#i",$argv[1])%2;

```
> 1 votes

# Answer
## Batch, 132 bytes

```
@echo off
set/ps=
set s=%s%%s:a=%%s:e=%%s:i=%%s:o=%%s:u=%
:l
if "%s%"=="" exit/b0
if "%s:~1%"=="" exit/b1
set s=%s:~2%
goto l

```

Takes input on STDIN, exits with `ERRORLEVEL` equal to `1` if the word is odd, `0` if it is even. Works by multiplying all the vowels by five and other letters by six, then calculating the parity of the resulting length.
> 1 votes

# Answer
# Turtlèd, ~~91 65 64 52 47~~ 67 bytes

More bytes because now takes case insensitive input

Changed approach again

does * for even, else o for odd

(trailing space)

```
!-u[*+.(a,)(e,)(i,)(o,)(u,)(A,)(E,)(I,)(O,)(U,)(*d(*'ou)(o'*u))_]'

```

It goes through input, writing it down on one square, each time there is a vowel, it moves down, flips the state of a the output cell, continues until EOF of input, then removes the cell where it writes down all the characters.
> 1 votes

# Answer
## Lua, ~~47~~ ~~44~~ 43 Bytes

```
print(#arg[2]:gsub('[^aeiouAEIOU]','')%2>0)

```

Takes the input via the command line, replaces all non-vowels with nothing, (removes them), prints true if the length of that is odd, false otherwise.

## Old submission

```
_,n=arg[2]:gsub('[aeiouAEIOU]','')print(n%2~=0)

```
> 1 votes

# Answer
## Go, 93 bytes

```
func(s string)int{n:=0;for _,c:=range s{for _,d:=range"aeiouAEIOU"{if c==d{n++}}};return n%2}

```
> 1 votes

# Answer
## R, 78 bytes

Solution is based on counting the number of vowels:

```
s=strsplit;w=s(readline(),"")[[1]];v=s("aeiouAEIOU","")[[1]];sum(w%in%v)%%2!=0

```

### Explanation

Unfortunately most functions in R relating to strings work on vectors of characters rather than full strings, thus the solution converts input into a vector using `strsplit` and checks whether this contains any vowels =\> sum the number of vowels and check if odd/even.

Also I found that using `v=s("aeiouAEIOU","")[[1]]` was shorter than manually inputting a vector of vowels which would have worked if only lower or upper case letters were used.
> 1 votes

# Answer
# R, 49 bytes

```
f=function(x)nchar(gsub("[^aeiou]","",x,i=T))%%2==0

```

Examples:

```
> f("cats")
[1] FALSE

> f("Savoie")
[1] TRUE

```

If it doesn't need a function and I can assume `x` is the input:

## 36 bytes:

```
!nchar(gsub("[^aeiou]","",x,i=T))%%2

```

If I can allow an output of 0 for even and 1 for odd:

## 35 bytes:

```
nchar(gsub("[^aeiou]","",x,i=T))%%2

```

# Explanation

I'm substituting all vowels with blank character, ignoring case (`i=T`). This works because the `i` is enough to unambigiously identify the `ignore.case` argument and `T` is short for `TRUE`. Then count the odd characters and see if there's a remainder. If a number isn't a good response, I use `!` (not) to coerce the 0/1 to TRUE/FALSE.
> 1 votes

# Answer
# T-SQL (SQL Server 2014), 217 bytes

## Golfed

```
declare @ table(a char)declare @i int=1while @i<=len(@a)begin insert into @ values(SUBSTRING(@a,@i,1))set @i=@i+1 end select count(*)%2from @ where a in('a','e','i','o','u')

```

## Usage

First declare the variable @a as a char of some sort and assign the input like so

```
declare @a varchar(max) = 'CAts'

```

Output will either be `1` for odd, or `0` for even

## Ungolfed

```
declare @input varchar(max) = 'rhythm'

declare @temp table ( letter char(1) ) -- table to hold each letter of the word

declare @i int = 1

while @i <= len(@input) -- split each letter, and each row in @temp will have one letter
begin
    insert into @temp values (SUBSTRING(@input, @i, 1))
    set @i = @i + 1
end

-- count the vowels and mod two to get if there's an even number of vowels or an odd number
select count(*) % 2
from @temp
where letter in ('a', 'e', 'i', 'o', 'u') -- use sql's case insensitive strings

```
> 1 votes

# Answer
# Groovy (39 Bytes)

```
{s->s.collect{/aeiou/=~it?1:0}.sum()%2}

```

https://groovyconsole.appspot.com/script/5195711326978048
> 1 votes

# Answer
## Julia, 53 Bytes

```
f(s)=sum(map(x->x in ["aeiouAEIOU"...]?1:2,[s...]))%2

```

replace odd characters with 1 and even characters with 2, then sum up. if the sum is even, then the word is even.
> 1 votes

# Answer
# , 27 bytes

```
Q_e\'a-'e-'i-'o-'u-e\;-e01?

```
> 1 votes

# Answer
# PHP, 91 bytes

```
foreach(str_split($argv[1])as$c)$n+=substr_count("AEIOU",strtoupper($c));if($n%2==0)echo 1;

```

Outputs `1` for even word, empty for odd word.

Test online

Testing code:

```
$wa = array('trees','brush','CAts','Savoie','rhythm');
foreach ($wa as $w) {
    $n = 0;
    foreach(str_split($w) as $c)
        $n+=substr_count("AEIOU",strtoupper($c));
    if ($n%2==0) echo 1;
}

```

Test online
> 1 votes

# Answer
## Racket 127 bytes

```
(if(= 0(modulo(for/sum((i(map(λ(i)(ormap(λ(x)(equal? i x))(string->list"aieouAEIOU")))(string->list s))))(if i 1 0))2))#f #t)

```

Ungolfed:

```
(define(f s)
  (let* ((vl (string->list "aieouAEIOU"))
         (od (λ(i) (ormap (λ (x) (equal? i x)) vl)))
         (ol (map od (string->list s)))
         (s (count (λ(i) i) ol ))
         (m (modulo s 2)))
    (if (= m 0) "even" "odd")
  ))

```

A longer (240 bytes) but more direct version:

```
(let*((vl(string->list"aieouAEIOU"))(od(λ(i)(ormap(λ(x)(equal? i x))vl))))(let lp((l(string->list s))
(st #t)(d 0))(cond((null? l)(if d"odd""even"))(st(lp(cdr l)#f(if(od(car l))#t #f)))
(else(lp(cdr l)#f(if(equal? d(od(car l)))#f #t))))))

```

Ungolfed:

```
(define (f s)
  (let* ((vl (string->list "aieouAEIOU"))
         (od (λ (i) (ormap (λ (x) (equal? i x)) vl) )))
    (let loop ((l (string->list s))
               (starting #t)
               (odd 0))
      (cond
        ((null? l)
         (if odd "odd" "even"))
        (starting
         (loop (rest l) #f
               (if(od (first l))
                  #t #f )))
        (else
         (loop (rest l) #f
               (if (equal? odd
                           (od (first l)))
                   #f #t)))))))

```

Testing:

```
(f "trees")
(f "brush")
(f "CAts")
(f "Savoie")
(f "rhythm")

```

Output:

```
"even"
"odd"
"odd"
"even"
"even"

```
> 1 votes

# Answer
# Ruby, 30 bytes

```
->w{w.count('aeiouAEIOU')%2>0}

```

Returns true for an odd word and false for an even word. The existing Ruby solution returns 0 for even words, which is a truthy value in Ruby.
> 1 votes

# Answer
# Elixir, 45 bytes

```
&rem(length(Regex.scan(~r/[aeiou]/i,&1)),2)>0

```

Anonymous function defined using the capture operator. If the number of vowels is odd, the specified word is odd, so the function returns true.

Full program with test cases:

```
s=&rem(length(Regex.scan(~r/[aeiou]/i,&1)),2)>0
# test cases
IO.puts s.("trees") # false
IO.puts s.("brush") # true
IO.puts s.("CAts")  # true
IO.puts s.("Savoie")    # false
IO.puts s.("rhythm")    # false

```

**Try it online on ElixirPlayground !**
> 1 votes

# Answer
# Python 2, 41 bytes

```
lambda s:sum(map(s.count,"aAeEiIoOuU"))%2

```

Try it online!

Returns 0 for even, and 1 for odd.

**Explanation:** Counts how many total odd letters are in the word, and returns whether that number is even (0) or odd (1).
> 1 votes

# Answer
# Kotlin, 32 bytes

0 is false, 1 is true.

```
{it.count{it in "aAeEiIoOuU"}%2}

```

Try it online!
> 1 votes

# Answer
# Z80Golf, 34 bytes

```
0000                restart:
0000   cd 03 80               call   $8003
0003   30 05                  jr   nc,letter
0005                done:
0005   78                     ld   a,b
0006   e6 01                  and   1
0008   ff                     rst   $38
0009   76                     halt
000a                letter:
000a   e6 1f                  and   $1f
000c   3d                     dec   a
000d   28 10                  jr   z,vowel
000f   d6 04                  sub   4
0011   28 0c                  jr   z,vowel
0013   d6 04                  sub   4
0015   28 08                  jr   z,vowel
0017   d6 06                  sub   6
0019   28 04                  jr   z,vowel
001b   d6 06                  sub   6
001d   20 e1                  jr   nz,restart
001f                vowel:
001f   04                     inc   b
0020   18 de                  jr   restart

```

Try it online!
> 1 votes

# Answer
# Pip, 9 bytes

```
-XV Na%:2

```

Try it online!

```
 XV        Regex matching [aeiou]
-          Case-insensitive
    N      Count matches in
     a     Command-line argument
      %:2  Mod 2 (the : helps with parsing)

```
> 1 votes

# Answer
# Clojure, 38 bytes

```
#(rem(count(re-seq #"(?i)[aeiou]"%))2)

```

Try it online!

This anonymous function outputs 1 for odd and 0 for even.

## Explanation

```
#"(?i)[aeiou]" ; This is a regular expression that matches a capital or lowercase vowel.
re-seq ; Returns a lazy sequence that contains all of the regex's matches from the input string.
count ; Returns the length of that sequence.
rem ; Returns the remainder when that length is divided by 2

```
> 1 votes

# Answer
# \>\<\>, 47 bytes

```
0i1+48*%:?v~2%n>~!
26a28*2b* \
r&:{=&+r  >l3(?v

```

Try it online!
> 1 votes

# Answer
# Factor, 34 bytes

```
[ [ "aeiouAEIOU"in? ] count odd? ]

```

Try it online!
> 1 votes

# Answer
# Regex (Perl / PCRE / Boost / Python<sup>`regex`</sup>) + `/i` flag, 24 bytes

```
^((.*?[aeiou]){2})*+(?2)

```

Returns a match if odd; returns no match if even.

Try it online! \- Perl
Try it online! \- PCRE
Try it online! \- Boost
Try it online! \- Python <sub><sup>`import regex`</sup></sub>

Explanation:

`^` \- Anchor to the beginning of the string

Each `(.*?[aeiou]){2}` matches the first two "odd" characters it finds, consuming them as it goes. The `(`...`)*+` wrapping it causes this to consume as many pairs as it can (minimum zero), where the `+` makes it a possessive quantifier, holding onto the first complete match (disabling backtracking).

At this point, the maximum even number of "odd" characters has been consumed, and if the word is "odd", exactly one "odd" character will remain, otherwise none will. `(?2)` attempts to match one more "odd" character, calling `(.*?[aeiou])` (group 2) as a subroutine.

# Regex (Ruby / PCRE) + `/i` flag, 25 bytes

```
^((.*?[aeiou]){2})*+\g<2>

```

Try it online! \- Ruby
Try it online! \- PCRE

This is a port of the Perl/PCRE/Boost regex to Ruby's style of subroutine call. This syntax is also supported by PCRE.

# Regex (Java or better) + `/i` flag, 29 bytes

```
^((.*?[aeiou]){2})*+.*[aeiou]

```

Try it online!

This is a port of the regex to flavors that have no subroutine calls, but do have possessive quantifiers.

# Regex (.NET or better) + `/i` flag, 32 bytes

```
^(?>((.*?[aeiou]){2})*).*[aeiou]

```

Try it online!

This is a port of the regex to flavors that have no subroutine calls or possessive quantifiers, so the clause `(`...`)*+` has been changed to `(?>(`...`)*)` to replace a possessive quantifier with an atomic group.

# Regex (ECMAScript or better) + `/i` flag, 36 bytes

```
^(?=(((.*?[aeiou]){2})*))\1.*[aeiou]

```

Try it online! \- ECMAScript
Try it online! \- Python

This is a port of the regex to flavors that have no subroutine calls, atomic groups, or possessive quantifiers, so the clause `(`...`)*+` has been changed to `(?=((`...`)*))\1` to replace a possessive quantifier with an emulation of an atomic group (using an atomic lookahead, group capture, and backreference).

# Regex (POSIX ERE or better) + `/i` flag, 51 bytes

```
^(([^aeiou]*[aeiou]){2})*[^aeiou]*[aeiou][^aeiou]*$

```

Try it online!

This is a port of the regex to flavors that have no subroutine calls and no way to disable backtracking.
> 1 votes

# Answer
# Zsh, 28 bytes

```
<<<$[${#1//[^aeiouAEIOU]}%2]
```

Attempt This Online!
> 1 votes

# Answer
# Kotlin, 39 bytes

```
{it.count{"aeiouAEIOU".contains(it)}%2}

```

Try it online!
> 1 votes

# Answer
# Arturo, 33 bytes

```
$=>[%match.count&"[aeiouAEIOU]"2]

```

Try it

Returns 0 for even, 1 for odd.
> 1 votes

# Answer
# **excel, 76 bytes**

```
=MOD(SUM(--(MID(A1,ROW(INDIRECT("1:"&LEN(A1))),1)={"a","e","i","o","u"})),2)

```

put the input in cell A1 and put the output formula in whichever other cell u want

returns 0 for even and 1 for odd

excel equates upper case and lower case letters when doing a direct comparison or something idk i just started using it for work and i'm still figuring it out
> 1 votes

# Answer
# Java 143 bytes

*Output is a boolean which is true if the word is odd.*

```
public static boolean isOdd(char c){
return c=='a'||c=='e'||c=='i'||c=='o'||c=='u';
}

public static boolean isOdd(String k){
  boolean y=false;
  for(char x:k.toLowerCase().toCharArray())
    if(isOdd(x))
      y=(y?false:true);
  return y;
}

```

Golfed:

```
boolean i(String k){boolean y=false;for(char c:k.toLowerCase().toCharArray())if(c=='a'||c=='e'||c=='i'||c=='o'||c=='u')y=!y;return y;}

```

***Edit:***

* Fixed Case-sensitivity
> 0 votes

# Answer
# Retina, ~~24~~ 21 bytes

```
i`[aeiou]
1
T`Ll`
11

```

(there's a mandatory additional empty line, but formatting ignores it)

Returns `1` for odd words, and *void* for even ones.

Try it online!
> 0 votes

# Answer
# Java, 59 bytes

```
s->s.chars().map(c->"aeiouAEIOU".indexOf(c)<0?0:1).sum()%2;

```

# Ungolfed test program

```
public static void main( String[] args )
{
    Function<String, Integer> func = s -> s.chars().map( c -> "aeiouAEIOU".indexOf( c ) < 0 ? 0 : 1 ).sum() % 2;

    System.out.println( func.apply( "cat" ) );
}

```
> 0 votes

# Answer
# Dyalog APL, 17 bytes

```
2|≢⍞∩'aeiouAEIOU'

```

TryAPL online!
> 0 votes

# Answer
# Lithp, 56 bytes

```
#S::((& 1 (~ (length (split S (regex "[aeiou]" "i"))))))

```
* Odd words: returns 1
* Even words: returns 0

This was one of my test cases for developing my language. It was modified extensively after this challenge was posted to support running code such as this.

---

This is the same logic as the JavaScript response above. The language is a simplistic Lisp-like dialect with a fairly small interpreter.

Ungolfed:

```
(
    (var F #S::(
        (var L (split S (regex "[aeiou]" "i")))
        (& 1 (~ (length L)))
    ))
    (print (call F "brush"))
)

```

There is not currently an online repl to test this in, but there is a variation of this challenge in one of the provided examples that can be run with the interpreter.
> 0 votes

# Answer
# Java, 128 bytes

```
boolean f(String k){return k.chars().flatMap(i->"aeiouAEIOU".contains(((char)i)+"")?IntStream.of(1):IntStream.of(0)).sum()%2>0;}

```

There's definitely a better way than using `Instream.of(0)` and `Instream.of(1)`.
> 0 votes

# Answer
# Pepe, 131 bytes

```
rEeEEeeeeErEeEEeeEeErEeEEeEeeErEeEEeEEEErEeEEEeEeEREeEeeeeeEREeeEeeeeeREEREEEerrEEEEEerEEeeREEEEReeReReREEeREEEEeeeRREeeeReEEEEReEE

```

Ouputs `0` for odd, `1` for even.

Try it online!
> 0 votes

# Answer
# Powershell, 39 bytes

```
($args|sls "[aeiou]"-a).Matches.Count%2

```

Explanation:

* Takes arguments from the predefined `$args`;
* Selects all matches to vowel characters (`sls` is alias for Select-String. By default, matches are not case-sensitive);
* Takes the Matches.Count, and %2 to check whether it's odd/even.

Test script:

```
$f = {

($args|sls "[aeiou]"-a).Matches.Count%2

}

@(
    ,("trees", $false)
    ,("brush", $true)
    ,("CAts", $true)
    ,("Savoie", $false)
    ,("rhythm", $false)

) | % {
    $s,$expected = $_
    $result = &$f $s
    "$($result-eq$expected): $result"
}

```

Output:

```
True: 0
True: 1
True: 1
True: 0
True: 0

```
> 0 votes

# Answer
**Java 8**: **88** bytes

```
s->s.chars().map(c->"aeiouAEIOU".contains((char)c+"")?-1:1).reduce(1,(x,y)->x*y)<0;

```

Try it online!
Dang it, I didn't see the older Java solution that used regex. Good job.
> 0 votes

# Answer
# Python 3, 42 bytes

```
lambda x:sum(c in"aeiouAEIOU"for c in x)%2

```

Try it online!
> 0 votes

# Answer
## brev, 62 bytes

```
(as-list odd?(c count(fn((as-list(c member x))"aeiouAEIOU"))))

```

Example:

```
(map
 (as-list odd? (c count (fn ((as-list (c member x)) "aeiouAEIOU"))))
 '("trees" "brush" "CAts" "Savoie" "even"))

=> (#f #t #t #f #f)

```
> 0 votes

# Answer
# Perl 5 `-p`, 19 bytes

*18 bytes for code; +1 byte for -p flag*

```
$_=s/[aeiou]//gi%2

```

Try it online!

Prints 0 for even words; 1 for odd.
> 0 votes

# Answer
## Pascal, 154 Bytes

This is a complete `program` according to ISO standard 7185 “Standard Pascal”.

```
program p(input,output);var n:integer;begin n:=0;repeat n:=n+ord(input^in['A','E','I','O','U','a','e','i','o','u']);get(input)until EOF;write(odd(n))end.

```

Ungolfed:

```
program oddWord(input, output);
var
    n: integer;
begin
    n := 0;

    repeat
    begin
        n := n + ord(input^ in ['A', 'E', 'I', 'O', 'U', 'a', 'e', 'i', 'o', 'u']);
        get(input);
    end
    until EOF(input);

    write(output, odd(n));
end.

```
> 0 votes

# Answer
# Thunno 2, 3 bytes

```
ṃSɗ

```

Attempt This Online!

#### Explanation

```
ṃSɗ  # Implicit input
ṃ    # For each letter: 1 if vowel, 0 if consonant
 S   # Sum the resulting list of 1s and 0s
  ɗ  # Get its parity (mod 2)
     # Implicit output

```
> 0 votes

---
Tags: code-golf, string, decision-problem
---


title: Is it a whole number?

text:
# Question
Title: Is it a whole number?
A number is whole if it is a non-negative integer with no decimal part. So `0` and `8` and `233494.0` are whole, while `1.1` and `0.001` and `233494.999` are not.

---

## Input

A floating-point number in the default base/encoding of your language.

For example, the default integer representation for Binary Lambda Calculus would be Church numerals. But the default integer representation for Python is *base 10 decimal*, not Unary.

## Output

A truthy value if the input is whole, a falsy value if it is not.

Note that if your language only supports decimal precision to, say, 8 places, `1.000000002` can be considered whole.

Input and output may be done via any standard I/O methods.

---

# Test cases

```
Input        -> Output
332          -> true
33.2         -> false
128239847    -> true
0.128239847  -> false
0            -> true
0.000000000  -> true
1.111111111  -> false
-3.1415926   -> false
-3           -> false

```

---

# Scoring

As with , the shortest submission wins. Good luck!

# Answer
> 14 votes
# APL (Dyalog), 3 bytes

```
⌊≡|

```

Try it online!

Note that `f←` has been prepended in the TIO link due to technical limitations, but it's not normally needed.

# Answer
> 16 votes
# Haskell, ~~27~~ 16 bytes

This function checks whether `x` is contained in the list of nonnegative integers that are not greater than `x`.

```
f x=elem x[0..x]

```

Try it online!

# Answer
> 10 votes
# Wolfram Language (Mathematica), ~~17~~ ~~15~~ 14 bytes

*Saved 1 byte thanks to Not a tree!*

```
#>=0==#~Mod~1&

```

Try it online!

First Mathematica answer \o/

## Mathematica, 15 bytes

*Saved 2 bytes thanks to @user202729!*

```
#==⌊Abs@#⌋&

```

# Answer
> 10 votes
# Pyth, 4 bytes

```
qs.a

```

Test suite

Is the number equal (`q`) to the floor (`s`) of its absolute value (`.a`)?

# Answer
> 6 votes
# Husk, 3 bytes

```
£ΘN

```

Try it online! The third test case times out in TIO, so I chopped off a couple of digits. I tried to run it locally, but killed it after a couple of minutes since it was using over 6GB of memory and my computer started to stutter. It should theoretically finish at some point...

## Explanation

This corresponds to the challenge description pretty directly.

```
£ΘN  Implicit input: a number.
  N  The infinite list [1,2,3,4...
 Θ   Prepend 0: [0,1,2,3,4...
£    Is the input an element of this list?

```

# Answer
> 6 votes
# Python 2, 18 bytes

```
lambda n:n%1==0<=n

```

Try it online!

# Answer
> 5 votes
# Python 2 and Python 3, ~~21~~ 18 bytes

```
lambda n:n>=0==n%1

```

Try it online! (Py2)
Try it online! (Py3)

3 bytes saved thanks to Mr. XCoder.

# Answer
> 5 votes
# ///, 94 bytes, input hard-coded

```
/=/\/x://:/\/\///-0/-:.0/.:.|/|:-|/|:0=1=2=3=4=5=6=7=8=9=|x/|:||/true:x:/-:/.:/|/+:++/false/||

```

Try it online!

Input between the two terminating vertical lines (`||`)

Strips `-00...0` and `.00...0`, converts all remaining digits to `x`s, then tests whether the remaining number still has `x`s after `.` or a `-` not followed by `.`.

Could save up to 7 bytes depending on what's counted as truthy and falsey since this language doesn't have native truthy/falsey values, currently is outputting `true` and `false` but could change to, for example, `T` and `F` for 87 bytes if that's allowed.

# Answer
> 5 votes
# Octave, 15 bytes

```
@(x)any(x==0:x)

```

Try it online!

This one is based on the approach used in @flawr's Haskell answer.

While it brings the byte count down to 15, it is shamefully inefficient (no offence intended), creating a list of every integer from `0` to `x` and seeing if `x` is contained within.

---

# Octave, 18 bytes

```
@(x)fix(x)==abs(x)

```

Try it online!

Takes input as a double precision number. Returns true if whole.

Checks if the input when rounded is equal to the magnitude of the input. This will only be the case when the number is positive and whole.

---

# Octave, 18 bytes

```
@(x)~mod(x,+(x>0))

```

Try it online!

An alternate solution for 18 bytes. Sadly the `mod` function in Octave won't implicitly convert a `bool` to a `double`, so the `+( )` is needed around the greater than comparison. Otherwise this solution would have been shorter.

---

# Octave, 18 bytes

```
@(x)x>=0&~mod(x,1)

```

Try it online!

And another one... ~~I can't seem to get lower than 18 bytes~~. All because of having to allow for 0 to be true with the `>=` instead of just `>`.

# Answer
> 5 votes
# C++ (gcc), 33 bytes

```
int f(float x){return(uint)x==x;}

```

Try it online!

# Answer
> 4 votes
# Pyth, 6 bytes

```
&gQZsI

```

Try it online!

# Answer
> 4 votes
# Aceto, 6 bytes

```
rfdi±=p

```

```
r grabs input
f converts it to a float
d and i duplicates it and converts it to an integer
± pushes the absolute value of it (b/c can't be negative)
= checks if they are equal
p prints out the result
```

Try it online!

# Answer
> 4 votes
# C (gcc), ~~27~~ ~~28~~ ~~27~~ 25 bytes

*<sup>-2 thanks to PrincePolka</sup>*

```
#define g(f)!fmod(f,f>=0)

```

Try it online!

Defines a macro "function" `g` that takes a parameter `f` (of any type). Then checks if casting `f mod 1` is zero, and if `f` is non-negative.

# Answer
> 4 votes
# QBIC, 17 bytes

```
?(:=int(a))*(a>0)

```

## Explanation

```
?             PRINT
 (:=int(a))     if the input (: assigns the cmd line param to 'a') equals itself
                cast to int, -1 else 0
 *              times
 (a>0)          if the input > 0, -1 else 0

```

If either check fails, this returns 0. If both are true, it returns -1 x -1 = 1

# Answer
> 4 votes
## C#, Java : 43 bytes

-1 byte thanks to Zacharý
-1 byte thanks to TheLetalCoder

```
int w(float n){return(n==(int)n&&n>=0)?1:0;}

```

C# has a special 33 bytes optimization that you can not do in java :

```
bool w(float n){return(int)n==n;}

```

### For testing

C# code :

```
class Program {
    int w(float n){return(n==(int)n&&n>=0)?1:0;}

    static void Main(string[] args)
    {
        var p = new Program();
        float[] fTab = new float[]{
            332,33.2f,128239847,0.128239847f,0,0.0000f,1.1111111111f,-3.1415926f,-3
        };
        foreach (float f in fTab) {
            Console.WriteLine(string.Format("{0} = {1}", f, (p.w(f) != 0).ToString()));
        }
        Console.ReadKey();
    }
}

```

Java Code :

```
public class MainApp {
    int w(float n){return(n==(int)n&&n>=0)?1:0;}

    public static void main(String[]a) {
        MainApp m = new MainApp();
        float testArr[] = new float[]{
                332,33.2f,128239847,0.128239847f,0,0.0000f,1.1111111111f,-3.1415926f,-3
        };

        for (float v : testArr) {
            System.out.println(v + " = " + String.valueOf(m.w(v)!=0));
        }
    }
}

```

# Answer
> 4 votes
# Google Sheets, 10 Bytes

Anonymous worksheet function that tales input from cell `A1` and outputs to the calling cell.

```
=A1=Int(A1

```

# Answer
> 4 votes
# Prolog (SWI), 24 bytes

```
f(X):-X>=0,round(X)=:=X.

```

Try it online!

# Answer
> 3 votes
# Ly, ~~35~~ 47 bytes

```
ir"-"=[0u;]pr[["0"=![psp>l"."=[ppr!u;]p<2$]pp]]

```

Try it online!

Ly has float support, but the only way to create a float currently is by performing division. There is no way to take a float as input, so I had to manually check the string instead.

Lost 13 bytes adding support for negative numbers.

# Answer
> 3 votes
# JavaScript, 14

```
n=>!(n<0||n%1)

```

# Answer
> 3 votes
# Perl 5, 11 +1(-p) bytes

```
$_=abs==int

```

The `-l` switch not counted because for tests display

try it online

# Answer
> 3 votes
## C, C++ : ~~38~~ 37 bytes

-1 byte thanks to Zacharý

-1 byte thanks to ceilingcat

```
int w(float n){return(int)n==n&n>=0;}

```

### For Testing

C : Try it online

C Code :

```
#include <stdio.h>
int main() {
    float f[] = { 332,33.2f,128239847,0.128239847f,0,0.0000f,1.1111111111f,-3.1415926f,-3 };
    int t;
    for ( t = 0; t < 9; ++t) {
        printf("%f = %s\n", f[t], w(f[t])?"true":"false");
    }
    return 0;
}

```

C++ Code :

```
#include <iostream>
int main() {
    std::initializer_list <std::pair<float,bool>> test{
        {332.f,true}, {33.2f,false}, {128239847.f,true}, {0.128239847f,false}, {0.f,true}, {0.000000f,true}, {1.111111f,false}, {-3.1415926f,false}, {-3.f,false}
    };

    for (const auto& a : test) {
        if (w(a.first) != a.second) {
            std::cout << "Error with " << a.first << '\n';
        }
    }
    return 0;
}

```

# Answer
> 3 votes
# C#, ~~40~~ ~~37~~ 29 bytes

```
bool z(float x)=>x%1==0&x>=0;

```

Saved 8 bytes thanks to @Dennis\_E!

Old Answer (37 bytes)

```
bool z(float x){return x%1==0&&x>=0;}

```

Old old answer (40 bytes):

```
bool z(float x){return (int)x==x&&x>=0;}

```

# Answer
> 3 votes
# Perl 6,  ~~15~~  13 bytes

```
{.narrow~~UInt}

```

Test it

```
{.Int==$_>=0}

```

Test it

# Answer
> 3 votes
# Java (OpenJDK 8), 14 bytes

```
n->n%1==0&n>=0

```

Try it online!

# Answer
> 3 votes
# JavaScript, ~~17~~ 15 bytes

```
_=>_<0?0:_==~~_

```
~~```
_=>_<0?0:_==(_|0)

```~~

Thanks to edc65 for catching my mistakes.

# Answer
> 3 votes
# Unexpanded Sinclair ZX81, 20 bytes

```
 1 INPUT A
 2 PRINT ABS A=INT A

```

20 bytes because BASIC is tokenized.

Simply will output 1 (true) if number is positive and the value of the number entered equals its integer value. Outputs 0 either of those conditions are not met.

# Answer
> 3 votes
# JavaScript (Node.js), 11 bytes

```
n=>n<0==n%1

```

Try it online!

# Answer
> 2 votes
# Jelly, 3 bytes

```
ḞA=

```

Try it online!

The algorithm is the same as the one used in the Mathematica answer above.

# Answer
> 2 votes
# Retina, ~~12~~ 10 bytes

Match the format of a non-negative whole number

```
^\d+\.?0*$

```

**Try it online**

*-2 thanks to FryAmTheEggman*

# Answer
> 2 votes
# , 7 4 bytes

Removed the unnecessary celing check after the solution of Erik The Outgolfer

```
<.=|

```

Try it online!

# Answer
> 2 votes
# Common Lisp, ~~36~~ 32 bytes

```
(lambda(n)(=(max n 0)(floor n)))

```

Try it online!

Transposition of marmeladze’s answer.

# Answer
> 2 votes
# Symbolic Python, 21 bytes

```
_=_%(_==_)==(_!=_)<=_

```

**Try it online!**

Uses a chained comparison:

* `_%(_==_) == (_!=_)` checks if `n%1 == 0`, only true if `n` has no decimal part.
* `(_!=_) <= _` checks if `0 <= n`, only true if the integer is non-negative.

# Answer
> 2 votes
# Implicit (version predating challenge), 10 bytes

```
÷±1>?{;;ö}

```

Try it online! (Will only work after Dennis pulls TIO for the eighteenth time, bugs are stupid)

```
÷±1>?{;;ö}   no implicit input :(
÷            read float
 ±1          push -1
   >         push (input > -1)
    ?{...}   if truthy
      ;      pop (input > -1)
       ;     pop -1
        ö    push iswhole(input)
             implicit integer output.
                if (input > -1) was false, it prints (input > -1).
                otherwise, it prints iswhole(input).

```

---

Posting this as an alternate solution since I had to update the builtin after realizing that whole numbers are \>= 0, which feels cheaty.

# Implicit, 1 byte

```
ö

```

Do *no* other languages have this builtin?!

```
   implicit float input
ö  push truthy if whole, falsy otherwise
   implicit int output

```

# Answer
> 2 votes
# Ruby, 17 bytes

```
->n{n>=0&&n%1==0}

```

Try it online!

It's not great, but I don't think it can get smaller.

# Answer
> 2 votes
# R, 30  ~~22~~ bytes

```
a=scan();`if`(a%%1==0&a>0,T,F)

```

# Answer
> 2 votes
# Brachylog, 7 bytes

```
⌋₁ℕ.&⌉₁

```

Try it online!

At first, I expected to submit a one-byte answer , which is a predicate meant to be equivalent to an assertion that the input (which is the output variable as well) is a whole number. Turns out, it doesn't consider integer-valued floats to be integers (throwing a false negative on the `0.00000000` test case, as well as the `1.0` non-test-case), so I had to do this instead:

```
           The input
⌋₁         rounded down
  ℕ        which is non-negative
   .       is the output variable
    &      and the input
     ⌉₁    rounded up
           is also the output variable.

```

# Answer
> 2 votes
# \>\<\>, 10 bytes

```
:1%$0(+0=n

```

Try it online!

**Explanation**

Calculates `(n%1 + n<0) == 0`

# Answer
> 2 votes
# TI-BASIC (TI-84), 3 bytes

```
not(fPart(Ans

```

**Example:**

```
3.5
             3.5
not(fPart(Ans
               0
21
              21
not(fPart(Ans
               1

```

Built-in functions are amazing, no?

Prints 0 (false) if `Ans` has a decimal part or 1 (true) if it doesn't.

# Answer
> 1 votes
# Japt, ~~6~~ ~~4~~ 3 bytes

```
¶Âa

```

Try it

---

## Explanation

Checks for strict equality () between the input and the absolute value (`a`) of the input with bitwise NOT applied twice (`Â`).

# Answer
> 1 votes
# Recursiva, 4 bytes

```
=aIa

```

Try it online!

# Answer
> 1 votes
# Python 3, ~~59~~ ~~57~~ 48 bytes

```
print("1")if float(input())%1==0else print("0")

```

Try it

# Answer
> 1 votes
## D : 43 bytes

Just discovered that D has strange cast rules. Code :

```
int w(float n){return n==cast(int)n&&n>=0;}

```

### For testing

D : Try it online

D Code :

```
void main() {
    float[] f = [ 332,33.2f,128239847,0.128239847f,0,0.0000f,1.1111111111f,-3.1415926f,-3 ];
    for (int t = 0; t < f.length; ++t) {
        writeln(f[t]," = ", w(f[t])?"true":"false");
    }
}

```

# Answer
> 1 votes
# MY, 8 bytes

```
ω≥ωω⌊=∧←

```

Try it online!

The link uses arrays to test multiple numbers at once.

## How?

* `ω≥` = `ω>=0` (`0` is popped when stack is empty)
* `ωω⌊=` = `ω==floor(ω)`
* `∧←` = take the logical and of the things above, then output.

# Answer
> 1 votes
# Clojurescript, 12 bytes

```
#(=(int %)%)

```

No TIO, this doesn't work in Clojure, only Clojurescript. You can try it here though:

```
cljs.user=> (def f #(=(int %)%))
#'cljs.user/f
cljs.user=> (f 2)
true
cljs.user=> (f 2.0)
true
cljs.user=> (f 2.5)
false

```

# Answer
> 1 votes
# Scala, 25 chars

```
(f:Double)=>f.ceil.abs==f

```

# Answer
> 1 votes
# PowerShell, 24 bytes

```
+"$args"-match'^[^-.]+$'

```

Try it online!

Convert the argument to a string, then back to a number (actually unnecessary, could have also just used `$args[0]` directly, but I thought of the latter first and it's the same byte count), then do a regex match, looking to see that the string has no `-` or `.` characters in its entirety.

Simple and boring :(

# Answer
> 1 votes
# PHP, 28 bytes

First solution:

```
echo!(ceil($n=$argv[1])-$n);

```

Second solution:

```
echo floor($n=$argv[1])==$n;

```

# Answer
> 1 votes
## Hexagony, 6 bytes

```
?~<%@'

```

Try it online!

Output via exit code. `1` for whole numbers and `0` otherwise.

### Explanation

Unfolded:

```
 ? ~
< % @
 ' .

```

If we try to read two integers, then the second one will be zero for whole numbers.

```
?    Read whole number part, N.
~    Multiply by -1.
<    This branches depending on whether the value is positive or not, i.e.
     whether N is negative or not.

     If it's negative, the IP moves SE.

'    Move the memory pointer backwards, to the right.
?    Read another value. Irrelevant.
%    Computes (0 % N). Irrelevant.
~    Multiply by -1. Irrelevant.
@    Terminate the program.

     If N isn't negative, the IP moves NE from the <.

?    Read the fractional part, F.
'    Move the memory pointer backwards, to the right.
%    Computes (0 % F). This terminates the program with exit code 1 if
     F is zero. Otherwise, it does nothing.
~    Multiply by -1. Irrelevant.
<    Reflect the IP to SW.
~    Multiply by -1. Irrelevant.
%    Computes (0 % F). Now irrelevant.
'    Move the IP back again.
@    Terminate  the program.

```

# Answer
> 1 votes
# Pyth - 10 Bytes

```
&qQ.EQgQ0

```

Explanation :

```
              Implicitly Print
&              And
    q           Are Equal
        Q        Input
        .E       Ceiling of
            Q     Input
    g           Greater Than or Equal to
        Q        Input
        0         0

```

# Answer
> 1 votes
# 05AB1E, 3 bytes

```
ïÄQ

```

Try it online or verify all test cases.

**Explanation:**

```
ï      # Trim all decimals of the (implicit) input
 Ä     # Take its absolute value
  Q    # Check if it's equal to the (implicit) input (and output implicitly)

```

# Answer
> 1 votes
## Scratch in scratchblocks2, ~~92~~ 67 bytes

thanks lirtosiast

```
when gf clicked
ask[]and wait
say<([abs v]of(answer))=(round(answer

```

Try it online

# Answer
> 1 votes
# PHP, 23+1 bytes

```
<?=$argn==abs(0|$argn);

```

prints `1` for truthy; empty output for falsy. Run as pipe with `-F`.

# Answer
> 1 votes
## Ruby, 18 characters

```
->x{x>=0&&0==x%1}

```

# Answer
> 1 votes
# Commodore BASIC (C64/128 C64Mini VIC-20...) 17 tokenized BASIC bytes

```
 0INPUTA:?A=INT(A)

```

In Commodore (Microsoft) 8-BIT BASIC, `-1` is `TRUE` and `0` is `FALSE`.

If you require strictly `1` to represent `TRUE` and `0` to represent `FALSE`, this is how to do it:

### Version 2, 20 tokenized BASIC bytes

```
 0INPUTA:?ABS(A=INT(A))

```

or

```
 0INPUTA:?-(A=INT(A))

```

# Answer
> 1 votes
# Vyxal, 2 bytes

```
⌊=

```

Try it Online!

```
⌊  # Floor
 = # Is equal to original?

```

# Answer
> 1 votes
# Thunno 2, 2 bytes

```
N=

```

Attempt This Online!

#### Explanation

```
N=  # Implicit input
N   # Cast to integer
 =  # Equals the input?
    # Implicit output

```

# Answer
> 0 votes
# JavaScript, ~~9~~ 12 bytes

```
n=>!n%1&n>=0

```

Didn't realize that I had to take in negatives. Pointed out by @kamoroso94.

# Answer
> 0 votes
# Ruby, 20 bytes

```
->x{x.div(1)==x.abs}

```

# Ruby, 22 bytes

```
->x{[0,x].max==x.to_i}

```

# Answer
> 0 votes
# C on Linux, 31 bytes

```
int f(float v){return!rintf(v);}

```

The correct prototype for rintf is `float rintf(float)`. However, in IEEE floating-point, 0.0f has the binary representation of all zeros. We (mis)use this feature to get away without using a prototype; the zero/non-zero value is then inverted into 1 or 0.

# Answer
> 0 votes
# Jq 1.5, 15 bytes

```
.>=0and.==floor

```

Not much to explain:

```
(. >= 0) and     # non-negative and
(. == floor)     # value == (value truncated to integer)

```

Try it online!

# Answer
> 0 votes
# , ~~36~~ ~~33~~ 30 bytes

```
T f(T)(T n){return(n<0)==n%1;}

```

Try it online!

I will not be beaten in D!

# Answer
> 0 votes
# Enlist, 4 bytes

```
:1Ae

```

Try it online!

Direct port of my Jelly answer above. Because of some reasons *HyperNeutrino* didn't implement Floor or Ceiling in Enlist, I use `:1` (integer division by 1) instead, which takes 2 bytes.

# Answer
> 0 votes
# Lua, 38 bytes

```
function f(n)print(n>=0 and n%1==0)end

```

Try it online!

# Answer
> 0 votes
## REXX, 27 bytes

```
arg n
say trunc(n)=n & n>=0

```

# Answer
> 0 votes
# Kotlin, 17 bytes

```
{it%1==.0&&it>=0}

```

Try it online!

# Answer
> 0 votes
# C + ecpp, 23 bytes

```
#def $x !fmod(x,1)&x>=0

```

Defines an operator `$` that takes one right operand `x` and evaluates to 1 if `x` is whole and 0 if it is not.

Try it online!

# Answer
> 0 votes
# Pyth, 4 bytes

Not a difficult question, but I thought I’d give it a try. Also did not think that zero was whole, but it saves a byte.

```
qs.a

```

Explanation:

```
 s.a      Integer of the absolute value of the implicit input
q         Is it the same as the original implicit input?

```

Test Suite

Version that doesn’t find `0` as a whole number:

```
&qs.a

```

Ands the original answer with the input, so `0` falsifies the answer.

Test Suite

Returns a falsy or truthy value that isn’t always a Boolean.

# Answer
> 0 votes
# Julia, 13 bytes

```
f(x)=x in 0:x

```

Try it online!

# Answer
> 0 votes
# ARBLE, ~~9~~ 7 bytes

```
nt(a%1)

```

Try it online!

# Answer
> 0 votes
# Pyt, ~~3~~ 4 bytes

```
Đ⎶Å≡

```

```
    implicit input
Đ   duplicates top value
⎶   pushes closest int to top value
Å   abs(TOS)
≡   checks if equal
    implicit output

```

Try it online!

# Answer
> 0 votes
# Taxi, 553 bytes

```
Go to Post Office:w 1 l 1 r 1 l.Pickup a passenger going to The Babelfishery.Go to The Babelfishery:s 1 l 1 r.Pickup a passenger going to Cyclone.Go to Cyclone:n 5 l 2 l.Pickup a passenger going to Trunkers.Pickup a passenger going to Equal's Corner.Go to Trunkers:s 1 l.Pickup a passenger going to Equal's Corner.Go to Equal's Corner:w 1 l.Switch to plan "b" if no one is waiting.'1' is waiting at Writer's Depot.[b]'0' is waiting at Writer's Depot.Go to Writer's Depot:n 1 l 1 r.Pickup a passenger going to Post Office.Go to Post Office:n 1 r 2 r 1 l.

```

Try it online!

Ungolfed:

```
Go to Post Office: west 1st left 1st right 1st left.
Pickup a passenger going to The Babelfishery.
Go to The Babelfishery: south 1st left 1st right.
Pickup a passenger going to Cyclone.
Go to Cyclone: north 5th left 2nd left.
Pickup a passenger going to Trunkers.
Pickup a passenger going to Equal's Corner.
Go to Trunkers: south 1st left.
Pickup a passenger going to Equal's Corner.
Go to Equal's Corner: west 1st left.
Switch to plan "b" if no one is waiting.
'1' is waiting at Writer's Depot.
[b]
'0' is waiting at Writer's Depot.
Go to Writer's Depot: north 1st left 1st right.
Pickup a passenger going to Post Office.
Go to Post Office: north 1st right 2nd right 1st left.

```

I'm surprised it took this long to post such a basic challenge. I like them. Taxi is... still not good for golfing.

# Answer
> 0 votes
# Jelly, 3 bytes

```
Ḟ⁼A

```

Try it online!

Uses Erik's strategy of `floor(n) == abs(n)`.

# Answer
> 0 votes
# Jelly, 3 bytes

```
AḞ=

```

Try it online!

# Answer
> 0 votes
# SNOBOL4 (CSNOBOL4), 73 bytes

```
	DEFINE('W(N)D')
W	N SPAN('1234567890') '.' REM . D
	W =EQ(D) 1	:(RETURN)

```

Try it online!

An anonymous function; returns `1` for truthy and an empty string for falsey.

Takes `N` the input and matches it against the regex `\\d.(\\d*)$`, setting `(\\d*)` as `D`. Then if `D==0` (`''==0` in SNOBOL), sets `W` to `1`. If not, it doesn't set `W`, which defaults to the empty string, and returns `W`.

# Answer
> 0 votes
## Javascript - 16 Bytes

`a=>a>=0&&a%1<=0`

```
f=a=>a>=0&&a%1<=0

// ----------- Test Cases -------------

console.log(332, f(332))
console.log(33.2, f(33.2))
console.log(128239847, f(128239847))
console.log(0.128239847, f(0.128239847))
console.log(0, f(0))
console.log(0.000000000, f(0.000000000))
console.log(1.111111111, f(1.111111111))
console.log(-3.1415926, f(-3.1415926))
console.log(-3, f(-3))
```

# Answer
> 0 votes
# TI-BASIC, 5 bytes

Takes input and gives output through `Ans`.

```
Ans=abs(int(Ans

```

# Answer
> 0 votes
# JavaScript (SpiderMonkey), 24 bytes

```
s=>s<0?0:s==Math.ceil(s)

```

Try it online!

A great thanks to @Jo King for converting the code from 29bytes to 24.

# Answer
> 0 votes
# Python 2, ~~59~~ ~~60~~ 57 bytes

```
lambda s:re.match(r"^\+?[0-9]+(\.0*)?$",s)>None
import re

```

Try it online!

Takes input as a string.

Regex is as follows:

* starts with + or a number
* has AT LEAST 1 digit
* either:
    + has a period, but only zeroes follow the period
    + has a period, but nothing after the period
    + terminates without a period

Python 2's re.match objects are greater than None objects, so it will return True if the regex matched and False otherwise.

Edit: no longer has false positives on negative numbers (not sure what i was thinking...) and correctly handles trailing periods. Thanks, Deadcode!

<sup><sub>I feel so bad about the greater than None check.</sub></sup>

# Answer
> 0 votes
# MathGolf, 3 bytes

```
i±=

```

Try it online!

## Explanation

Same as a bunch of other answers.

```
i     Read input as integer
 ±    Convert to absolute value
  =   Is it equal to the implicit input?

```

# Answer
> 0 votes
# Gol\>\<\>, 17 bytes

```
I:0(q0h:S(-zq1!0h

```

A simple solution, but I will be golfing this *alot* more

Try it online!

# Answer
> 0 votes
# Runic Enchantments, 6 bytes

```
i:kn=@

```

Try it online!

Works on inputs up to 65535. Compares the input with the input cast to character and back to number. Inputs larger than 65535 cast to char exceed the byte size and roll over.

# Answer
> 0 votes
# cQuents, 4 bytes

```
?$-1

```

Try it online!

## Explanation

```
?        Given input n, output true if n is in the sequence and false if it is not
         Each term in the sequence equals
 $        current index
  -1                    - 1

```

The `-1` in to include `0` \- if the challenge just wanted positive integers, `?$` would be enough.

# Answer
> 0 votes
# Stax, 2 bytes

```
1%

```

Run and debug it

Modulus by 1.

---
Tags: code-golf, number, decision-problem, integer
---


title: Calculator that adds char values

text:
# Question
Title: Calculator that adds char values
# Task

Build a calculator, that takes any string, from a file, stdin or whatever, and adds up all the values of the chars.

Example

```
Input
Hello World!

Output
1085

```

# Rules

The calculator needs to accept just ASCII encoding.

The shortest code wins.

# Notes

Regarding to the comment of m.buettner, I need to say, I didn't thought of the multibyte part.
So I leave it as a bonus thing aswell.
The calculator should be run as written, so no need to modify before compiling or interpreting.

# Bonus

Thanks to Synthetica, here is one more bonus,

> The program that has the lowest output when you use its code as its input wins gets a star.

I don't want to modify it completly.

If you write it additional to output the (right) value in UTF-8 you get a star.

The code that executes fastest on my Laptop (Lenovo Yoga 13 Intel Core i5 3317U 1.7Ghz, 8GB RAM, 128GB SSD, Intel HD 4000, Windows 8) gets a star.

Web codes will run first under IE11 with chakra and then in FireFox 29.0.1 with SpiderMonkey

Linux code will run on a Raspberry Pi with Raspbian.

The teststring is this:

```
q/%8hnp>T%y?'wNb\},9krW &D9']K$n;l.3O+tE*$*._B^s!@k\&Cl:EO1zo8sVxEvBxCock_I+2o6 yeX*0Xq:tS^f)!!7=!tk9K<6#/E`ks(D'$z$\6Ac+MT&[s[]_Y(`<g%"w%cW'`c&q)D$0#C$QGf>?A$iawvc,}`9!('`c&q)D$0#C$QGf>?A$iawvc,}`9!(

```

Have fun coding :)

# Bonusscoring

I plan to do the scoring at this Saturday so the 07.06.14, all answers after that date won't get bonus points ;)

You can download the code I gonna use for testing here feel free to fork and improve it :)

Little update because of the bonus, my laptop is partially broken so I will do it probably next weekend, I am really sorry for that :(

# Answer
> 10 votes
# GolfScript, 4 characters

```
{+}*

```

Simply uses the fold operator (`*`) to add up all the characters.

If it has to work with the empty string, 9 chars:

```
{{+}*}0if

```

Thanks to @PeterTaylor for providing an alternative 6-char version that works with empty string:

```
0\{+}/

```

# Answer
> 7 votes
# APL (8)

```
+/⎕UCS⍞

```

Explanation:

* `+/` sum of
* `⎕UCS` unicode values of
* character input

# Answer
> 6 votes
# Haskell 36

```
main=interact$show.sum.map fromEnum

```

# Answer
> 6 votes
# Shell+GNU tools, 29 bytes

```
echo `od -An -tuC`|tr \  +|bc

```

Takes input from stdin:

```
$ printf "%s" 'Hello World!' | ./addchars.sh
1085
$

```

Own score: 2385

---

# c, 52 bytes

```
c;main(p){while(~(p=getchar()))c+=p;printf("%d",c);}

```

Compile with (some warnings produced):

```
gcc addchars.c -o addchars

```

Takes input from stdin:

```
$ printf "%s" 'Hello World!' | ./addchars
1085 $

```

Own score: 4354

# Answer
> 6 votes
# Javascript (*ES6*) 51

```
alert([...prompt(x=0)].map(y=>x+=y.charCodeAt())|x)

```

# Answer
> 6 votes
# 8086 Assembly (16-bit) - 47 41 bytes

The contents of the `test.com` file are:

```
98 01 c3 b4 01 cd 21 3c 0d 75 f5 89 c7 c6 05 24
89 d8 b1 0a 4f 31 d2 f7 f1 80 ca 30 88 15 09 c0
75 f2 89 fa b4 09 cd 21 c3

```

Actual work is done in the first 11 bytes; I need the rest to print the result in decimal notation.

Source code (give as input to the DOS `debug.com` assembler):

```
a
; input the string; count the sum
    cbw
    add bx, ax
    mov ah, 1
    int 21
    cmp al, d
    jne 100
; Prepare for output: stuff an end-of-line marker
    mov di, ax
    mov [di], byte 24
    mov ax, bx
    mov cl, a
; 114
; Divide by 10; write digits to buffer
    dec di
    xor dx, dx
    div cx
    or  dl, 30
    mov [di], dl
    or  ax, ax
    jne 114
; Print the string
    mov dx, di
    mov ah, 9
    int 21
    ret

rcx 29
n test.com
w
q

```

Some notes on the code:

* Only handles one line (up to end-of-line character 13); hangs if no end-of-line
* Only 7-bit characters are supported (results are incorrect otherwise)
* Outputs 0 for empty input
* Cannot handle output greater than 64K
* Instruction at address 0x10d overwrites itself (pure coincidence)
* Have to use DOS emulators like DosBox to assemble and run this program

# Answer
> 6 votes
# gs2, 1 byte

```
d

```

`d` (`0x64` / `sum`), of course, sums up all bytes in standard input.

# Answer
> 5 votes
## Ruby, ~~13~~ 12 bytes

```
p~9+gets.sum

```

`sum` is a built-in function that sums the characters of a string. Subtracts 10 to account for the newline at the end of `gets`'s return value.

(Edited 4 years later to change `x-10` to `~9+x`... the value of `~9` is `-10`, but it lets us remove the space between `p` and its argument, saving a byte.)

# Answer
> 5 votes
# CJam, 3 bytes (sum 260)

```
q1b

```

You can try it online.
Thanks jimmy23013 for helping chop off 2 characters :)

**Explanation:**

```
q     read the input into a string
1b    convert from base 1, treating each character as its numeric value

```

# Answer
> 4 votes
# Python 3 - 28 bytes

```
print(sum(map(ord,input())))

```

Example run:

```
$ ./sum_string.py <<< 'Hello World!'
1085

```

Gets input from stdin, `map`s the `ord` function to it to get the ASCII value of each character, `sum`s it and `print`s.

# Answer
> 4 votes
## Befunge98, 6 bytes, sum: 445

```
2j@.~+

```

Any interpreter should be fine. I use CCBI.

Use as follows:

```
printf 'Hello World!' | ccbi calc.fg

```

Works for multibyte chars and empty strings.

**Explanation**

* `2j` \- jump over the next two instructions (`@` and `.` \- see below)
* `~` \- put the next char on the stack
* `+` \- add the code value of the new char to the current sum. The instruction pointer wraps to the beginning and the cycle repeats
* when `~` encounters an EOF it inverses the direction of the pointer and the two "hidden" instructions are executed:
* `.` \- print the sum
* `@` \- exit

# Answer
> 4 votes
# Python, 24 bytes

This is shorter than any Python solution so far: an unnamed anonymous function, which takes the string as an argument, and returns the sum.

```
lambda x:sum(x.encode())

```

**Try it online!**

First, `x.encode()` transforms it into a `bytes` object. Then, `sum` adds the char-code values. As this is a lambda function, the value is implicity returned.

Additionally, one could have `lambda x:sum(map(ord,x))` for the same byte count.

# Answer
> 2 votes
# Julia - ~~11~~ 7 characters, resultant sum = ~~943~~ 536

Since the question allows the input to come from whatever source you want, I choose an existing variable. Assume that `A` contains the string we wish to evaluate.

```
sum(A)1

```

As it turns out, you can sum the string directly, and it will evaluate... however, due to the way that summing of chars is handled, if there is an odd number of characters in the string, it will output a character, rather than an integer of any sort. As such, we force it to cast to int by multiplying by 1.

Old version:

```
sum(A.data)

```

Will output in a hexadecimal notation (if the sum is less than 256, it'll be `0x??`, otherwise it'll be 8 byte as `0x????????`). If used in code where the result is used, it will operate just like any other number (it's just how Julia displays unsigned ints).

To see the value of the result in decimal, enclose the above in `int()`, as in `int(sum(A.data))`.

For anybody who doesn't know Julia, you assign to `A` exactly the same way you do other assignments to variables. So, `A="Hello World!"` or `A="sum(n.data)"`. In the case where you need to put in `"` or `'` characters, there are multiple options, the easiest of which (because it avoids need for knowledge of the nuances of Julia string literals) is `A=readline()`, followed by simply typing in the string into STDIN (won't handle newlines, though). The escape sequence for newline is, as usual, `\n`, but I don't believe you can use that with readline().

# Answer
> 2 votes
# Go (59 characters)

```
func d(s string)(t int){for _,x:=range s{t+=int(x)};return}

```

Everything in Go is utf8 by default. Codetext in \` delimeters run through itself gives an output of: 5399.

# Answer
> 2 votes
## PowerShell - 27

```
[char[]]$args[0]|measure -s

```

**Example**

```
> SumChars.ps1 'Hello World!'

Count    : 12
Average  :
Sum      : 1085
Maximum  :
Minimum  :
Property :

```

# Answer
> 2 votes
# SML, ~~42~~ 36

Just adding another language.

```
fun$x=foldl op+0(map ord(explode x))

```

Converts String to char array, calculates ascii number of each value and calculates the sum of all ascii numbers.

# Answer
> 2 votes
# K5, 2 bytes (function), 5 bytes (program)

## Function

```
+/

```

## Program

```
+/0:`

```

Not sure if K5 was created before or after this challenge was posted. Regardless...THIS IS AWESOME!!

In K5, if you perform arithmetic operations on strings, it converts the characters to their ASCII codes. So this just uses the sum operator `+/` (actually, it's plus + over).

# Answer
> 2 votes
# Matlab/Octave 4 bytes (bonus: 405)

This code is an anonymous function, that does the job, it will take a string, and return the required number.

```
@sum

```

# Answer
> 2 votes
# Javascript ES6, 41 bytes

```
_=>[..._].map(y=>x+=y.charCodeAt(),x=0)|x

```

*Thanks to @ETHproductions for 2 bytes saved!*

# Answer
> 2 votes
# Gol\>\<\>, 4 bytes

```
iEh+

```

# Answer
> 2 votes
# Jolf, 2 bytes

Try it here!

```
ui
u  sum of
 i  the input string

```

Umm... I don't know what else to say.

# Answer
> 2 votes
# Vyxal, 2 bytes

```
C∑

```

Try it Online!

### Explained

```
C∑
C  # char
 ∑ # sum

```

# Answer
> 1 votes
# J (7)

So close, yet so far... Oh well, I guess 7 is decent enough, since this answer also accepts empty strings. (I'm basing my usage of a variable as input on the phrase `from a file, stdin or whatever`)

```
+/a.i.b

```

## Explanation:

```
a.

┌┬┐├┼┤└┴┘│─ !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~��������������������������������������������������������������������������������������������������������������������������������

```

`a.` contains all ASCII chars.

```
   'people' i. 'pow'
0 2 6

```

`x i. y` is similar to python's `[x.index(i) for i in y]`.

```
   a. i. 'Hello World!'
72 101 108 108 111 32 87 111 114 108 100 33

```

Therefor, `a. i. y` converts `y` to an array of its ASCII values

```
   +/1 2 3 4 5 6
21

```

`+/` is like `sum`: `+/1 2 3 4 5 6` means `1+2+3+4+5+6`

```
   +/ a. i. 'Hello World!'
1085

```

The whole thing in action

For the bonus:

```
   b=:'+/a.i.b'
   +/a.i.b
482

```

Not bad, I guess.

```
   b=:'0\{+}/'
   +/a.i.b
478

```

Well, darn.

```
   A=:'+/a.i.A'
   +/a.i.A
449

```

Thanks @algorithmshark

```
    A=:'+/3 u:A'
    +/3 u:A
413

```

Thanks @marinus

# Answer
> 1 votes
## JavaScript (ES6) 54 58

```
alert([].reduce.call(prompt(),(v,c)=>v+c.charCodeAt(0),0))

```

54 bytes thanks to **nderscore**:

```
alert([...prompt()].reduce((v,c)=>v+c.charCodeAt(),0))

```

# Answer
> 1 votes
# C 32

```
f(char*s){return*s?*s+f(s+1):0;}

```

# Answer
> 1 votes
## D (function: 60)

Definitely not in it to win it.

Assuming it doesn't need to be a complete program

```
int c(string i){int s;foreach(e;i){s+=cast(int)e;}return s;}

```

Called like so

```
void main ()
{
    import std.stdio;
    auto hw = "Hello World!";
    writefln("%s = %d", hw, c(hw));
}

```

Output:

```
Hello World! = 1085

```

## D (program: 133)

Does not count line breaks.

```
void main(){import std.algorithm,std.stdio;stdin.byLine.map!((a){int s;foreach(e;a){s+=cast(int)e;}return s;}).reduce!"a+b".writeln;}

```

With more whitespace and longer variable names for readability

```
void main () {
    import std.algorithm, std.stdio;

    stdin.byLine
        .map!((line) {
                int sum;
                foreach (ch; line) {
                    sum += cast(int)ch;
                }
                return sum;
            })
        .reduce!"a+b"
        .writeln;
}

```

To support line breaks in the input, I could either use `byLine(KeepTerminator.yes)` — the correct way, for 20 characters — or append a `'\n'` to my line — which breaks single-line input and may give the wrong sum on Windows because of CRLF, for 18 characters.

# Answer
> 1 votes
## R, ~~35 characters (sum of 3086)~~ 26 bytes (sum of 2305)

```
sum(utf8ToInt(readline()))

```

`readline()` is one character longer than `scan(,"")` but `scan` split the input on spaces by default.

Usage:

```
> sum(utf8ToInt(readline()))
Hello World!
[1] 1085
> sum(utf8ToInt(readline()))
sum(utf8ToInt(readline()))
[1] 2305
> sum(utf8ToInt(readline()))
q/%8hnp>T%y?'wNb\},9krW &D9']K$n;l.3O+tE*$*._B^s!@k\&Cl:EO1zo8sVxEvBxCock_I+2o6 yeX*0Xq:tS^f)!!7=!tk9K<6#/E`ks(D'$z$\6Ac+MT&[s[]_Y(`<g%"w%cW'`c&q)D$0#C$QGf>?A$iawvc,}`9!('`c&q)D$0#C$QGf>?A$iawvc,}`9!(
[1] 14835

```

# Answer
> 1 votes
# Delphi (87 83)

```
function x(s:string):int64;var c:char;begin x:=0;for c in s do x:=result+ord(c)end;

```

### Ungolfed

```
function x(s:string):int64;
var
  c:char;
begin
  x:=0;
  for c in s do
    x:=result+ord(c)
end;

```

Loops through `S` adding the `ord` value of the char to the result. where x==result

## Edits:

Saved 4 characters by switching to int64 and changing the adding to the sum.

# Answer
> 1 votes
# k (8 chars)

```
+/6h$0:0

```

Q translation

```
sum `int$read0 0

```

Bonus value:

```
k)+/6h$0:0
+/6h$0:0
438i

```

# Answer
> 1 votes
## Java 8 - 79 bytes

```
interface C{static void main(String[]a){System.out.print(a[0].chars().sum());}}

```

# Answer
> 1 votes
# Japt, 6 bytes

```
U¬mc x

```

Pretty simple. Try it online!

### How it works

```
U¬mc x  // Implicit: U = input string
U¬      // Split U into chars.
  mc    // Map each item to its char code.
     x  // Sum.
        // Implicit: output last expression

```

# Answer
> 1 votes
# PlatyPar, 2 bytes

```
us

```

Try it online!

`u` generates an array of all charcode values in the input string, and `s` finds their sum.

When run on itself, it returns `232`.

This is similar to Conor's Jolf answer, except that I use a byte to convert the string into an array of character codes (which is implicit in Jolf), whereas he uses a byte to retrieve the input (which is implicit in PlatyPar).

# Answer
> 1 votes
## JavaScript function golf, 77 bytes

```
var s=i();var x=0;for(var i1=0;i1<sl(s);i1++){x+=schca(s,i1);}console.log(x);

```

I made this for you!

Yes, you got it right, it's my own function golf again. It recently got a string functions update.

The language was created after the challenge, so it's non-competing.

Validity source:

```
>>> var s=i();var x=0;for(var i1=0;i1<sl(s);i1++){x+=schca(s,i1);}console.log(x);
Hello World!
1085

```

Bonus score:

```
>>> var s=i();var x=0;for(var i1=0;i1<sl(s);i1++){x+=schca(s,i1);}console.log(x);
var s=i();var x=0;for(var i1=0;i1<sl(s);i1++){x+=schca(s,i1);}console.log(x);
6276

```

# Answer
> 1 votes
# Unipants' Golfing Language, 8 bytes

```
cIl+I:_o

```

Try it online!

Returns 660 given its own source code.

## Explanation

```
cIl+I:_o
c        # Create an integer. We need it - you'll see why.
 I       # Input the first character.
  l  :   # While loop.
   +     # Add the character value to the integer. This is
         # why we needed an integer. Otherwise, there would
         # only be 1 item in a stack now, and the "+" op is
         # not defined for this case. In fact, it returns 0
    I    # Input the next character.
      _  # Discard a zero (the zero from the last input,
         # representing the End Of Line).
       o # Output the result.

```

# Answer
> 1 votes
# Java 8, 113 chars

```
BigInteger C(String s){BigInteger i=BigInteger.ZERO;s.chars().forEach(x->i=i.add(BigInteger.valueOf());return i;}

```

*Note* each character in Java is Unicode 1-4 bytes unsigned integer, using `sum` function would easily overflow.

**Detailed**

```
BigInteger C (String s)
{
    BigInteger i = BigInteger.ZERO;

    s.chars().forEach(x -> i = i.add(BigInteger.valueOf(x));

    return i;
}

```

# Java 8, 57 chars

*ASCII only solution*

```
int C(String s){return s.chars().filter(x->x<128).sum();}

```

**Detailed** try here

```
public static int C (String s)
{
    return s
        .chars() // stream the characters
        .filter(x -> x < 128) // filter ASCII (optional)
        .sum(); // return the sum
}

```

# Answer
> 1 votes
# JavaScript (ES6), 37 bytes

```
f=([c,...a])=>c?c.charCodeAt()+f(a):0

```

This uses a handy feature, new in ES6: destructuring assignments. When run, the variable `c` gets set to the first char in the string, and `a` gets set to the rest of the string as an array.

# Answer
> 1 votes
# Cubix, 10 bytes

```
OU@;i)!^(+

```

Test it online!

This is almost the perfect challenge for Cubix, which can only input one char code at a time. This code expands to the following cube net:

```
    O U
    @ ;
i ) ! ^ ( + . .
. . . . . . . .
    . .
    . .

```

The code is then run, starting at the `i` and facing east. Here's the main loop:

* `i` \- input a char code from STDIN and push it to the stack. Pushes -1 on EOF.
* `)` \- increment the top item.
* `!` \- if the top item is non-zero, skip the next instruction.
* `(` \- decrement the top item.
* `+` \- add the top two items. Note: the stack has infinite zeroes at the bottom.
* `.` \- no-op.

When EOF is reached, the `!` fails, and `^` forces the instruction pointer to move north onto the top face. Then this code is run:

* `;` \- pop the top item (currently a 0).
* `U` \- turn 180 degrees counter-clockwise. This is used to fit `;O@` on the top face.
* `O` \- output the top item (sum of char-codes) as a number.
* `@` \- terminate the program.

# Answer
> 1 votes
# Minkolang, 6 bytes

```
$o$+N.

```

Try it online!

### Explanation

```
$o         takes all characters from input as chars (the characters are automatically
           converted to their character codes)
$+         sum up all the values
N.         output as number and end program

```

# Answer
> 1 votes
# 05AB1E, 2 bytes

```
ÇO

```

Try it online.

**Explanation:**

```
Ç   # Convert each character in the (implicit) input to its unicode value
 O  # Sum this list of integers
    # (after which the result is output implicitly)

```

# Answer
> 1 votes
# PHP, 46 bytes

No PHP answer on this yet, so here's the easy one:

```
<?=array_sum(array_map(ord,str_split($argn)));

```

Try it online!

```
$ echo Hello World!|php -F addascii.php
1085

```

### More non-competing answers:

**48 bytes**

Iterative:

```
foreach(str_split($argn)as$s)$x+=ord($s);echo$x;

```

Try it online!

**51 bytes**

Iterative 2:

```
while($i<strlen($argn))$x+=ord($argn[$i++]);echo$x;

```

Try it online!

**63 bytes**

Recursive:

```
function f($s,$c=0){return$s?f(substr($s,1),ord($s[0])+$c):$c;}

```

Try it online!

**69 bytes**

Using PHP's rarely used <sub>\[citation needed\]</sub> `array_reduce()` function:

```
<?=array_reduce(str_split($argn),function($c,$i){return$c+ord($i);});

```

Try it online!

# Answer
> 1 votes
# Keg, 2 bytes

```
?⅀

```

Try it online!

## Explanation

```
?  # Read the full input string
 ⅀ # Sum the whole stack
# Implicit output

```

# Answer
> 1 votes
## , 2 bytes

The Join function also works with numbers.

```
CJ

```

## , 4 bytes

Terribly golfed answer...

```
C@+R

```

# Answer
> 1 votes
# Fig, \\$1\log\_{256}(96)\approx\\$ 0.823 bytes

```
S

```

Try it online!

# Answer
> 0 votes
# Lua 57

```
a=io.read();b=0;for i=1,#a do b=b+a.byte(a,i)end print(b)

```

Sucks that it's the longest by a long shot, but whatever.

# Answer
> 0 votes
# C# in LINQPad, 28

```
Console.ReadLine().Sum(i=>i)

```

# Answer
> 0 votes
## C 63

```
main(a,b)char**b;{a+=*b[1];*b[1]++?main(a,b):printf("%d",a-2);}

```

# Answer
> 0 votes
# Perl 33

```
$_=<>;$x+=ord for split'';print$x

```

I don't know Perl too well. I'm sure it can be golfed some more.

# Answer
> 0 votes
# Cobra - 81

```
class P
    def main
        c,d=Console.readLine,0
        for i in c,d+=i to int
        print d

```

# Answer
> 0 votes
## J (9 chars)

In the REPL, we only need 6 chars:

```
   +/a.i.'Hello World!'
1085

```

To make it a re-usable program, we need to add 3 chars of decoration:

```
   as=: [: +/ a.&i.
   as 'Hello World!'
1085

```

# Answer
> 0 votes
## Common Lisp, 35

```
(reduce'+(read-line):key'char-code)

```

Produces 3053 when given its own code.

# Answer
> 0 votes
# jq, 12 characters

(11 characters code + 1 character command line option.)

```
explode|add

```

Sample run:

```
bash-4.3$ bin/jq -R 'explode|add' <<< 'Hello World!'
1085

```

On-line test (Passing `-R` through URL is not supported – so input passed as string "Hello World!".)

(CW because `explode` appeared in jq 1.4, released 4 days after this question.)

# Answer
> 0 votes
# \>\<\>, 19 bytes

```
0i:1+?!v+!
    ;n~<

```

It does work on Unicode. For example, this correctly outputs 27272 : `⚳ℚ⊻`

Try it here

# Answer
> 0 votes
## Perl, 34 32 27 25 21+1=22 bytes

Added 2 due to the need for -p flags. Thanks to @manatwork for the guidance.

```
$a+=ord for/./g;$_=$a

```

Test:

```
echo 'Hello World!' | perl -pe '$a+=ord for/./g;$_=$a'
1085

```

# Answer
> 0 votes
## Perl 22

```
s/./$t+=ord$&/eg;say$t

```

sample:

```
perl -nE 's/./$t+=ord$&/eg;say$t'  < <(echo -n Hello\ World\!)
1085

```

# Answer
> 0 votes
# Java, 144 bytes (sum of 13067)

```
interface S{static void main(String[]A){int I=0;for(char J:new java.util.Scanner(System.in).nextLine().toCharArray())I+=J;System.out.print(I);}}

```

# Answer
> 0 votes
# Mathematica, 19 bytes

```
Tr@*ToCharacterCode

```

Test case:

```
Tr@*ToCharacterCode@"Hello World!"
(* 1085 *)

```

# Answer
> 0 votes
# 2, 5 chars / 13 bytes

```
⨭ ᴉ⒨⒞

```

`Try it here (Firefox only).`

Splits and maps the input to its charcodes, then sums the resulting array.

# Answer
> 0 votes
# Mathcad, 11 "bytes"

Uses Mathcad's built-in vector summation operator. As "whatever" is an input method, the user types the word directly into the argument for the function str2vec (which converts a string to a vector of its character codes).

# Answer
> 0 votes
## C++, 131 ~~140~~ bytes

### Golfed:

```
#include<iostream>
int main(){int a=0;std::string x;getline(std::cin,x);for(int c=0;c<x.length();c++){a=a+(int)x[c];}std::cout<<a;}

```

### Ungolfed:

```
#include<iostream>

int main(){
    int a = 0;
    std::string x;
    getline(std::cin, x);
    for(int c = 0; c < x.length(); c++){
        a = a + (int) x[c];
    }
    std::cout<<a;
}

```

# Answer
> 0 votes
## Java, 139 Bytes

//takes input from cmd line args

```
class P {public static void main(String a[]){String s=a[0];int v=0;for(int i=0;i<s.length();i++){v+=(int)s.charAt(i);}System.out.print(v);}}

```

It's big, but yeah.

# Answer
> 0 votes
# Factor, 3 bytes

```
sum

```

Strings are sequences, arrays of char values. `sum` is basically `0 [ + ] reduce` (or, equivalently, `[ + ] foldl`), so this sums the chars in a string.

# Answer
> 0 votes
# Mathcad, 13 "bytes"

Uses built-in vector summation operator and string-to-vectorOfCharacterCodes function. Definition operator ":=" entered by single key ":", summation operator by ctl-4.

# Answer
> 0 votes
# Python 3, 37 bytes

```
print(sum([ord(c) for c in input()]))

```

There's a shorter one, but this is possible as well. It converts the string into a list will all the ASCII values of the characters and adds them together using `sum()`.

# Star version, 55 bytes

```
a=sum([ord(c) for c in input()]);print(a);print(chr(a))

```

Now gimme my gold star.

# Answer
> 0 votes
# Clojure, 31 bytes

```
#(reduce +(map int(read-line)))

```

Really straightforward. Gets its input from stdin, works with Unicode.

# Answer
> 0 votes
## Hoon, 18 bytes

```
|*
*
(roll +< add)

```

This is a wet gate, so that I don't have to specify `tape` instead of `*`. This has the added bonus of it being fully generic, so it could actually accept `(list @ud)` too. Wet gates typecheck at the call site, instead of definition.

`+<` is the sample of the gate, indexed into the sample with tree navigation syntax because it's shorter than naming the function arguments. `|*(a/* a)` is longer than `|*(* +<)`.

```
> %.  "Hello World!"
  |*
  *
  (roll +< add)
b=1.085

```

Unfortunately, this doesn't work correctly as-is with unicode. Urbit's string literals are lists of UTF8 chars. You can use `++tuba` to convert it to UTF32, though.

```
> %.  "⚳ℚ⊻"
  |*
  *
  (roll +< add)
b=1.622

> %.  (tuba "⚳ℚ⊻")
  |*
  *
  (roll +< add)
b=27.272

```

# Answer
> 0 votes
# Pushy, 2 bytes

```
S#

```

**Try it online!**

Input is automatically converted to charcodes and placed on the stack. `S` sums the stack, and `#` prints it.

# Answer
> 0 votes
# Brainfuck - 15 Bytes

```
,[>,]<[[<+>-]<]

```

Try it here (You have to click the box marked "!")

Put your input after the exclamation point. (not necessary but allows easy EOF.)

## What it does

```
,[>,]     take input as characters in separate cells until input has ended (automatically in ascii)
<         go to the last character
[         infinite loop
[<+>-]    add the last character and the character before it and save it as the last character
<]        go back to the last character and then do the infinite loop again

```

Unfortunately, it exits with an out of memory error and does not print the output, but that wasn't part of the challenge. If you want to see the output, read the tape. It also only goes up to 255 on this interpreter. (if anyone knows an interpreter with larger cells that exits on error, that would be great)

# Answer
> 0 votes
# Perl 5 `-pF`, 15 bytes

Under the rules in place at the time of this challenge, I believe it would have been +3 for the command line flags, giving a score of 18.

```
map$\+=ord,@F}{

```

Try it online!

# Answer
> 0 votes
# Whitespace, 61 bytes

```
[S S S N
_Push_0][N
S S N
_Create_Label_LOOP][S N
S _Duplicate_top][S N
S _Duplicate_top][T N
T   S _Read_STDIN_as_character][T   T   T   _Retrieve_input][S N
S _Duplicate][S S S T   S T S N
_Push_10][T S S T   _Subtract][N
T   S S N
_If_0_Jump_to_Label_PRINT][T    S S S _Add][N
S N
N
_Jump_to_Label_LOOP][N
S S S N
_Create_Label_PRINT][S N
N
_Discard_newline][T N
S T _Output_top_as_integer]

```

Letters `S` (space), `T` (tab), and `N` (new-line) added as highlighting only.
`[..._some_action]` added as explanation only.

Since Whitespace inputs one character at a time, the input should contain a trailing newline so it knows when to stop reading characters and the input is done.

Try it online (with raw spaces, tabs, and new-lines only).

**Explanation in pseudo-code:**

```
Integer s = 0
Start LOOP:
  Integer c = Read STDIN as character
  If(c == 10) // c == '\n'
    Call function PRINT
  s = s + c
  Go to next iteration of LOOP

function PRINT:
  Discard the top of the stack (the 10 / newline)
  Print s as integer to STDOUT

```

# Answer
> 0 votes
# C# (Visual C# Interactive Compiler), 14 bytes

```
s=>s.Sum(x=>x)

```

Try it online!

# Answer
> 0 votes
# Unexpended Sinclair ZX80 - 65 tokenized BASIC bytes

```
 1 INPUT A$
 2 LET A=0
 3 IF A$="" THEN GO TO 7
 4 LET A=A+CODE(A$)
 5 LET A$=TL$(A$)
 6 GO TO 3
 7 PRINT A

```

There are a few caveats, without `POKE`ing some (or one, I don't recall) memory location(s), all maths is done via 16-bit signed integers, so the range is -32768 to +32767, so any string entered that is too long will overflow the `VAR` stack and break the program. Also, the ZX80 character set is not ASCII compatible and there is no exclamation mark, so `HELLO WORLD` (as there are no lower-case characters by default either) is `494` \- source.

BASIC does not update the screen whilst doing calculations and such, so after entering the string it will take some time to work out where nothing will be displayed. Your original string entered in the `A$` variable will not show.

# Answer
> 0 votes
# Ahead, 5 bytes

```
SK+O@

S      slurp input
 K+    reduce stack by summing
   O   output sum
    @  end

```

Try it online!

# Answer
> 0 votes
# Kotlin, 22 bytes

`(String) -> Int` lambda.

```
{it.sumBy{it.toInt()}}

```

Try it online!

# Answer
> 0 votes
# Runic Enchantments, 10 bytes (Self-sum: 703)

```
iul1)?@+2?

```

Try it online!

It has a limit on how long of a string it can handle. For a version that can handle any length string:

```
/l͍:i0< /~~@
R1-:0≮?/:}}:{%3s}+}

```

Try it online! (Self-sum: 3937)

In both cases spaces need to be escaped in order to be read as a single input. The first one works by unconcatening the string and iteratively adding each character together until only a single value is left (printing it).

The second uses an index pointer and extracts one character at a time, adding it to a running total (requiring more in the way of setup and stack manipulation).

# Answer
> 0 votes
# Japt `-mx`, 1 byte

```
c

```

Try it!

---

If the input cannot be an array of chars, then this can be done in 3 bytes:

```
¬xc

```

Try it!

# Answer
> 0 votes
## , 4 bytes

Seems like a perfect task for @.

```
Σš

```

Explanation

```
Σ  Summation of
 š a one-line input

```

# Answer
> 0 votes
# Brain-Flak, 6 bytes (own code sum: 577)

```
({{}})

```

Try it online!

Seems to be a good challenge for Brain-Flak.

**Explanation:**

```
 {  }   while top of Stack is not 0, calculate sum of
  {}    pop value
(    )  push calculated sum
        implicitly output the Stack

```

# Answer
> 0 votes
# Wren, 35 bytes

The fact that they aren't doing this in Wren is a perfect chance for me.

```
Fn.new{|x|x.bytes.reduce{|a,i|a+i}}

```

Try it online!

## Explanation

```
Fn.new{|x|                        } // New anonymous function with parameter x
          x.bytes                   // Convert x to its bytecode forms
                 .reduce{|a,i|a+i}  // Sum this bytecode form

```

# Answer
> 0 votes
# Pyth, 3 bytes

```
sCM

```

Try it online!

Alternatively, `smC` works as well.

**Explanation:**

```
    # implicit output
s   # sum(                )
  M #     map(   ,       )
 C  #         ord
    #             input()   -> implicit input

```

# Answer
> 0 votes
# K (ngn/k), 2 bytes

```
+/

```

Try it online!

In K, a string is basically a list of ASCII char codes, so just the sum adverb will do the job.

# Answer
> 0 votes
# Go, 58 bytes

```
func f(b[]byte)(s int){for _,e:=range b{s+=int(e)}
return}

```

Attempt This Online!

# Answer
> 0 votes
# Raku, 10 bytes

```
*.ords.sum

```

Try it online!

The `ords` string method conveniently returns a list of the ordinal values of the characters.

# Answer
> 0 votes
# Thunno 2 `SB`, 0 bytes

Attempt This Online!

Or, **2 bytes** flagless:

```
CS

```

Attempt This Online!

---
Tags: code-golf
---