ASCII Sum of a String

easy Strings

Problem

Read one line of printable ASCII text (spaces are allowed). Print the sum of the ASCII codes of all its characters. For example a is 97 and A is 65.

Constraints

  • 1 <= length <= 10^5

Examples

Input

abc

Output

294

Solutions

Best approachTime O(n)Space O(1)

Each character is stored as a number. Java adds a char to an int directly, JavaScript needs charCodeAt and Python needs ord.

Same code works in Java810172125Basic features only, so nothing changes between versions.
/*
 * Problem : Process text.
 * Input   : One line of text.
 * Output  : The sum of codes.
 * Approach: Add each character code.
 * Time    : O(n)
 * Space   : O(1)
 * Java    : 8 or newer.
 */
import java.util.Scanner;

public class Main {
    // This method solves the task. It receives the input and returns the answer.
    static long solve(String s) {
        // Step 1: A char is a number in Java. Adding it to an int gives its code.
        long total = 0;
        for (int i = 0; i < s.length(); i++) {
            total += s.charAt(i);
        }
        return total;
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String s = scanner.hasNextLine() ? scanner.nextLine() : "";
        System.out.println(solve(s));
    }
}
Hints (1)
  1. Which function gives the code of a character in Python?