ASCII Value of a Character
Problem
Read one line. Print the ASCII code of its first character. For example A is 65, a is 97 and 0 is 48.
Constraints
- The line has at least one printable ASCII character
Examples
Input
A
Output
65
Solutions
Every character has a number in the ASCII table. Capital letters start at 65 and small letters start at 97. The difference between them is 32.
/*
* Problem : Find the code.
* Input : One line of text.
* Output : The code of the first character.
* Approach: Character codes.
* Time : O(1)
* 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 int solve(String s) {
// Step 1: A char is stored as a number. Casting it to int shows the number.
char first = s.charAt(0);
return (int) first;
}
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)
- What is the difference between A and a?