Interview Question for SDE-2s


Country: United States




Comment hidden because of low score. Click to expand.
1
of 1 vote

for this simple questions, make sure all border cases, overflows, etc. are covered.
as well, maybe define the allowed token/string exactly (e.g. using regexp)
that would be "\s*0x[0-9a-zA-Z]+\s*"

#include <string>
#include <iostream>
#include <locale>

using namespace std;

int hexCharToInt(char c)
{
	if (c >= '0' && c <= '9') return c - '0';
	if (c >= 'A' && c <= 'F') return 10 + c - 'A';
	if (c >= 'a' && c <= 'f') return 10 + c - 'a';
	throw "unexpected character";
}

unsigned long hex2int(const string& str) 
{
	size_t i = 0;
	while (i < str.size() && isspace(str[i])) i++; // trailing spaces
	if (i == str.size()) throw "unexpected end of string"; // string must not consist of only white-spaces
	if (str[i++] != '0') throw "unexpected character"; // a 0x must initiate the hex string
	if (i == str.size()) throw "unexpected end of string";  // 0 is not a valid hex string
	if (str[i++] != 'x') throw "unexpected character"; // 0x to initiate hex string
	if (i == str.size()) throw "unexpected end of string"; // string must not end now
	if (isspace(str[i])) throw "unexpected character"; // no space allowed after "0x"
	unsigned long value = 0;
	while(i < str.size() && !isspace(str[i])) {
		unsigned long or = value;
		value <<= 4;
		if (value >> 4 != or) throw "overflow";
		value |= hexCharToInt(str[i]);
		i++;
	}
	while (i < str.size() && isspace(str[i])) i++; // trailing spaces, if any
	if (i < str.size() - 1) throw "unexpected character"; // no other characters expected
	return value;
}


int main()
{
	cout << hex2int("0x0") << endl;
	cout << hex2int("  0x80") << endl;
	cout << hex2int("  0xff  ") << endl;
	cout << hex2int("  0xffffffff  ") << endl;
	cout << hex2int("  0x1fffffff1  ") << endl; // should throw overflow exception
	cout << hex2int("  1fffffff1  ") << endl; // should throw unexpected char exception
}

- Chris August 23, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

//java8

int convertFromHex(char[] s) {
        int digit, result = 0, i = (s[0] == '0') && (s[1] == 'x' || s[1] == 'X') ? 2 : 0;
        for (; i < s.length; i++) {
            char c = s[i];
            if (c >= '0' && c <= '9') {
                digit = c - '0';
            } else if (c >= 'A' && c <= 'F') {
                digit = 10 + c - 'A';
            } else {
                throw new IllegalArgumentException("not hex");
            }

            try {
                result =
                        Math.addExact(Math.multiplyExact(16, result),
                                digit);
            } catch (Exception e) {
                throw new IllegalArgumentException("overflow", e);
            }

        }
        return result;
    }

- Makarand August 25, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class HexToDecimal {

    public static void main(String[] args) {
        System.out.println(convertFromHex("36F9BFB3"));
    }

    static int convertFromHex(String str) {
        char[] s = str.toUpperCase().toCharArray();
        int digit, result = 0, i = (s[0] == '0') && s[1] == 'X' ? 2 : 0;
        for (; i < s.length; i++) {
            char c = s[i];
            if (c >= '0' && c <= '9') {
                digit = c - '0';
            } else if (c >= 'A' && c <= 'F') {
                digit = 10 + c - 'A';
            } else {
                throw new IllegalArgumentException("not hex");
            }

            try {
                result =
                        Math.addExact(Math.multiplyExact(16, result),
                                digit);
            } catch (Exception e) {
                throw new IllegalArgumentException("overflow", e);
            }

        }
        return result;
    }
}

- Makarand August 26, 2017 | Flag Reply


Add a Comment
Name:

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.

Books

is a comprehensive book on getting a job at a top tech company, while focuses on dev interviews and does this for PMs.

Learn More

Videos

CareerCup's interview videos give you a real-life look at technical interviews. In these unscripted videos, watch how other candidates handle tough questions and how the interviewer thinks about their performance.

Learn More

Resume Review

Most engineers make critical mistakes on their resumes -- we can fix your resume with our custom resume review service. And, we use fellow engineers as our resume reviewers, so you can be sure that we "get" what you're saying.

Learn More

Mock Interviews

Our Mock Interviews will be conducted "in character" just like a real interview, and can focus on whatever topics you want. All our interviewers have worked for Microsoft, Google or Amazon, you know you'll get a true-to-life experience.

Learn More