#578Easy· asked at 1 company
Find the ASCII Value of a Character
Problem
Given a single character c, return its ASCII (Unicode code point) value. As follow-ups: convert an integer back to its character, and explain how character arithmetic ('a' + 1, c - '0') works.
Input / Output
- Input: character
c. - Output: integer.
Examples
| Input | Output |
|---|---|
'A' | 65 |
'a' | 97 |
'0' | 48 |
' ' | 32 |
'~' | 126 |
Constraints
cis a printable ASCII character (32–126).
Approach
Every language exposes the code point directly: ord(c) in Python, (int) c in C/C++/Java, c.charCodeAt(0) in JavaScript. The reverse is chr(n) / (char) n / String.fromCharCode(n).
What interviewers actually probe with this warm-up:
- Digits
'0'..'9'are contiguous (48–57), soc - '0'converts a digit character to its numeric value. - Uppercase
'A'..'Z'are 65–90 and lowercase'a'..'z'are 97–122; they differ by 32, which is whyc ^ 32toggles case andc | 32lowercases. - Building a frequency array indexed by
ord(c) - ord('a')is O(1) per character and is the basis of many string problems. - Beyond ASCII,
ordreturns the Unicode code point; UTF-8 byte length is a separate concept.
Complexity
- Time: O(1)
- Space: O(1)
Reference solution (Python)
def ascii_value(c: str) -> int:
return ord(c)
def char_from(n: int) -> str:
return chr(n)
Test cases
| Input | Expected |
|---|---|
'A' | 65 |
'a' | 97 |
'0' | 48 |
char_from(126) | '~' |