Read a Number Typed as Text
Solve this ProblemEasy10 min
Topics
BasicsInputStrings
Companies
TCSInfosysWipro
Given the characters a user typed,
text, return the number they represent multiplied by 2.
Whatever a user types — on a keyboard or into a test file — reaches the program as textStandard InputThe stream a program reads typed input from. It always delivers characters, never numbers.. Java reads it with Scanner or BufferedReader.readLine(), Python with input(), C++ with cin or getline, C with scanf or fgets, and JavaScript with a line reader. Even when the user types 21, a line-based read hands back the two characters '2' and '1', not the number twenty-one. (Helpers like nextInt() or cin >> n look like they read numbers, but they do this same conversion internally.) On this site the reading is done for you and the text arrives as the text parameter; your job is the next step every input-handling program needs — turning that text into a number you can do arithmetic with. Doubling the result proves the conversion worked: done wrong, "21" becomes "2121" instead of 42.
Test Case 1:
Input:text = "21"
Output:42
Explanation:The text "21" becomes the int 21, and 21 × 2 = 42 — not the text "2121".
Test Case 2:
Input:text = "007"
Output:14
Explanation:Leading zeros do not change the value: "007" is the number 7.
Constraints
- ◆
1 ≤ text.length ≤ 9 - ◆
text contains only the digits 0-9 - ◆
0 ≤ the number in text ≤ 100000000
Try the Dry Run
Approach & Solutions
Digit-by-Digit ConversionGood
Every character is stored as a code, and the codes for '0'..'9' are consecutive, so ch - '0' gives the digit's value. Walk the text left to right; for each digit, shift what you have one decimal place left (multiply by 10) and add the new digit. After the last character, value holds the real number, ready to be doubled.
Time
O(n)Space
O(1)Java
class Solution {
public int doubleTypedNumber(String text) {
int value = 0;
for (int i = 0; i < text.length(); i++) {
int digit = text.charAt(i) - '0';
value = value * 10 + digit;
}
return value * 2;
}
}Built-in ParserOptimal
Every language ships a function that does the digit-by-digit work for you: Integer.parseInt in Java, int() in Python, stoi in C++, atoi in C and parseInt in JavaScript. Convert once, then do real arithmetic on the number.
Time
O(n)Space
O(1)Java
class Solution {
public int doubleTypedNumber(String text) {
int value = Integer.parseInt(text);
return value * 2;
}
}