Convert a String to a Long
Updated
Problem statement
Given a string s that holds a base-10 integer, convert it to a 64-bit signed integer (a long) and return it.
Work through the characters yourself. Do not pass the string to a built-in number parser such as Long.parseLong, int(), stoll, strconv.ParseInt, Number() or BigInt().
s may start with one '+' or '-' sign, and its digits may have leading zeros. The value of s always fits in a long.
Function
stringToLong(s: String) → longExamples
Example 1
s = "123"return = 123Read the digits from left to right: 1, then 1 * 10 + 2 = 12, then 12 * 10 + 3 = 123.
Example 2
s = "-0042"return = -42The minus sign makes the result negative. Leading zeros do not change the value, so the digits give 42 and the answer is -42.
Example 3
s = "+9223372036854775807"return = 9223372036854775807This is the largest value a long can hold, 2^63 - 1. The plus sign does not change the value.
Example 4
s = "-9223372036854775808"return = -9223372036854775808This is the smallest long, -2^63. Without the sign, its digits make 9223372036854775808, which is one more than the largest long. So building the positive number first and then negating it overflows in languages with fixed-size integers.
Constraints
1 <= s.length <= 30sis an optional'+'or'-'followed by one or more digits'0'to'9'.- The value of
sis between-2^63and2^63 - 1, inclusive.
More Zillow interview questions
- Build a Hash TableOA · PHONE SCREEN · ONSITE INTERVIEW · Seen Feb 2023
- First Unique Character in a StringOA · PHONE SCREEN · ONSITE INTERVIEW · Seen Oct 2022
- Cumulative Fibonacci SumOA · PHONE SCREEN · Seen Aug 2021
- First N Fibonacci NumbersOA · PHONE SCREEN · ONSITE INTERVIEW · Seen Jun 2021
- Insert and Delete in a Trinary TreeOA · Seen May 2016
- Find the Four Missing Numbers in a FileOA · PHONE SCREEN · Seen Feb 2014
- Valid ParenthesesPHONE SCREEN · ONSITE INTERVIEW · Seen Jul 2025
- Reversible Run-Length EncodingPHONE SCREEN · Seen Nov 2022
- Lowest Common Ancestor in a Binary TreePHONE SCREEN · Seen Sep 2019
- LRU CachePHONE SCREEN · ONSITE INTERVIEW · Seen Oct 2016
Similar questions at other companies
- Identification Number Check DigitAbridge · OAAbridge interview questions
- Count Substrings With Identical CharactersVirtu Financial · OAVirtu Financial interview questions
- Count Multiples of Three with Two SevensHudson River Trading · OAHudson River Trading interview questions
- Is This Date a Weekend?Salesforce · OASalesforce interview questions
- Triple-Position Alphabet EncodingArm · OA
- Closest ColorTwo Sigma · OATwo Sigma interview questions
- Prime Number From a StringAdobe · OAAdobe interview questions
- Sum Integer StringsIntuit · OAIntuit interview questions
- Digit Changes for a Multiple of 9Nutanix · OANutanix interview questions
- Count Times Using at Most Two DigitsLSEG · OALSEG interview questions