Microsoft Interview Question for SDE-3s


Country: United States
Interview Type: In-Person




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

c#, overflow is not handled.

string str = "107080023";
Dictionary<char, int> dic = new Dictionary<char, int>(){ {'0', 0}, {'1', 1}, {'2', 2}, {'3', 3}, {'4', 4}, {'5', 5}, {'6', 6}, {'7', 7}, {'8', 8}, {'9', 9}, };
int pos = str.Length - 1;
int res = 0;
int @base = 1;
while( pos >= 0 ) {

  res += dic[ str[ pos ] ] * @base;
  @base *= 10;
  pos--;

}
Console.WriteLine( res );

- zr.roman January 18, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
1
of 1 vote

I think the question is not about converting the string into integer. If we read the question again carefully, the string may be of billions/trillions of length.
like, string inp = "123411213232323232323232323232323232323232 and so on......";
Then, how to convert it into an integer ?

- Rajkumar January 21, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

I suppose that when you need integer value of the string, this mean that string has upper bound ( 2^32 -1) , because it represent integer or i didn't get anything?

- EPavlova January 18, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

as far as I get it, the meaning of "integer" here is not from standpoint of datatypes, but from standpoint of floating point (sorry for unintentional pun).
E.g. a number 1.000.000.000.000.000.000.000.000 in terms of task is also an integer, though rather a big one.

- zr.roman January 18, 2016 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Yes there would be a physical limit on the upper bound of the integer (like Integer.MAX_INT in java), this doesn't change the algorithm. You can use the numbers provided as examples. And test for edge cases etc.

- william.brandon.lee83 January 18, 2016 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

int convertString(String num) {
	  int res = 0;	
	  boolean isNeg = false;
	  if (num.charAt(0) == '-')	  
		  isNeg = true;	  
	  else 
		  res= res * 10 +(num.charAt(0) - '0');
	   for (int i = 1; i < num.length(); i++) {
		  res= res * 10 +(num.charAt(i) - '0');
	  }	 
	  return isNeg ? - res : res;
  }

- EPavlova January 19, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

but this is cheating, because compiler makes type casting for you behind the scenes.

- zr.roman January 19, 2016 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

In C/C++, strings are char arrays terminated by '\0'

int _tmain(int argc, _TCHAR* argv[])
{
	char s[] = "1000352";
	int sum = 0;
	for (char *p = s; *p != '\0'; p++)
	{
		int i = *p - '0';
		sum = sum * 10 + i;
	}

	

	return 0;
}

- PT January 19, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Just a little thought, but the check in the for {*p != '\0'} can simply be written as {*p} in C because the null character equates to 0 (or false) and all other characters equate to a number (or true).

- gsawers January 20, 2016 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

int _tmain(int argc, _TCHAR* argv[])
{
	char s[] = "1000352";
	int sum = 0;
	for (char *p = s; *p != '\0'; p++)
	{
		int i = *p - '0';
		sum = sum * 10 + i;
	}

	

	return 0;
}

- PT January 19, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

void convert(string strNum)
{ 
	long unsigned int iUL = 1;
	int i=1;
	int len  = strNum.length();
	while(i<len)
	{	
		iUL = (iUL *10)+(strNum[i]-'0');
		i++;
	}
	cout << '\n'<< iUL;
}

- sv January 19, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

unsigned __int64 convert(unsigned char* InputString)
{
// We assume that we always have a string for a positive value - no sign

	int iLength;
	unsigned char* pInputBegin;
	unsigned char* pInputCurrent;
	unsigned char* pInputEnd;
	unsigned __int64 uiResult;
	unsigned __int64 uiMultiplier;

// First, we find the end of the string (assuming there is no number bigger than 10**100 in the Universe):
	pInputCurrent = InputString;
	pInputBegin = InputString;
	iLength = 0;
	while (*pInputCurrent != NULL)
	{
		if (iLength >= 100)
		{
			return 0; // the number is too big
		}
		
		++pInputCurrent;
		++iLength;
	}

	pInputEnd = pInputCurrent; // now we point to the last string character

	uiResult = 0;
	uiMultiplier = 1;

	while (pInputCurrent >= pInputBegin)
	{
		uiResult = uiResult + uiMultiplier * (*pInputCurrent - 48); // ASCII characters 48...57 correspond to digits 0...9
		uiMultiplier = uiMultiplier * 10;
		--pInputCurrent;
	}

	return uiResult;
}

- sergey.a.kabanov January 19, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class StringToNum {
	
	public static void main(String[] args)
	{
		String numString = "1000322";
		long num = convert(numString);
		System.out.println(num);
	}

	private static long convert(String numString) {
		
		long num = 0;
		int i=1, pos = numString.length(), helper=0;
		while(pos > 0)
		{
			pos -= 1;
			helper = Integer.parseInt(numString.substring(pos, pos+1));
			if(helper != 0)
			{
				num += helper * (Math.pow(10, i-1));
			}
			i++;
		}
		
		return num;
	}

}public class StringToNum {
	
	public static void main(String[] args)
	{
		String numString = "1000322";
		long num = convert(numString);
		System.out.println(num);
	}

	private static long convert(String numString) {
		
		long num = 0;
		int i=1, pos = numString.length(), helper=0;
		while(pos > 0)
		{
			pos -= 1;
			helper = Integer.parseInt(numString.substring(pos, pos+1));
			if(helper != 0)
			{
				num += helper * (Math.pow(10, i-1));
			}
			i++;
		}
		
		return num;
	}

}

- Sigma January 20, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include <cstdio>
#include <cmath>
#include <iostream>
#include <string>
#include <vector>

using namespace std;

vector<int> convert(string inp) {
	// Assumption: no leading 0's in input
	int blockSize =  static_cast<int>(log(pow(2,sizeof(int)*8 - 1))/log(10));
	int length = inp.length();
	int sign = (inp[0]=='-')?1:0;
	int size = (length-sign)/blockSize + 1;
	vector<int> result(size);

	for(int i=sign;i<length;i++) {
		int cur = (blockSize - length%blockSize + i-sign)/blockSize;
		result[cur] = result[cur]*10 + (inp[i]-'0');
	}
	if(sign) result[0] *= -1;
	return result;
}


int main()
{
	string inp= "-3234567890";

	vector<int> result = convert(inp);
	for(vector<int>::iterator it = result.begin();it!=result.end();it++) {
		cout << *it;
	}
	cout << endl;
	return 0;
}

- Sam January 20, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include <cstdio>
#include <cmath>
#include <iostream>
#include <string>
#include <vector>

using namespace std;

vector<int> convert(string inp) {
	// Assumption: no leading 0's in input
	int blockSize =  static_cast<int>(log(pow(2,sizeof(int)*8 - 1))/log(10));
	int length = inp.length();
	int sign = (inp[0]=='-')?1:0;
	int size = (length-sign)/blockSize + 1;
	vector<int> result(size);

	for(int i=sign;i<length;i++) {
		int cur = (blockSize - length%blockSize + i-sign)/blockSize;
		result[cur] = result[cur]*10 + (inp[i]-'0');
	}
	if(sign) result[0] *= -1;
	return result;
}


int main()
{
	string inp= "-3234567890";

	vector<int> result = convert(inp);
	for(vector<int>::iterator it = result.begin();it!=result.end();it++) {
		cout << *it;
	}
	cout << endl;
	return 0;
}

- Sam January 20, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include <cstdio>
#include <cmath>
#include <iostream>
#include <string>
#include <vector>

using namespace std;

vector<int> convert(string inp) {
	// Assumption: no leading 0's in input
	int blockSize =  static_cast<int>(log(pow(2,sizeof(int)*8 - 1))/log(10));
	int length = inp.length();
	int sign = (inp[0]=='-')?1:0;
	int size = (length-sign)/blockSize + 1;
	vector<int> result(size);

	for(int i=sign;i<length;i++) {
		int cur = (blockSize - length%blockSize + i-sign)/blockSize;
		result[cur] = result[cur]*10 + (inp[i]-'0');
	}
	if(sign) result[0] *= -1;
	return result;
}


int main()
{
	string inp= "-3234567890";

	vector<int> result = convert(inp);
	for(vector<int>::iterator it = result.begin();it!=result.end();it++) {
		cout << *it;
	}
	cout << endl;
	return 0;
}

- alif666 January 20, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

In Python int(<str_representation>) would do the job. But as per logic, we can have something like:-

a = "12345"

res = 0
for char in a[:]:
    val = ord(char) - 48
    res = res*10 + val

print res

- Barun Sharma January 20, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

C# implemetation

public static void Run()
        {
            string input = "107080023";
            int result = 0;
            for(int i = 0; i < input.Length; i++)
            {
                // handled for "-" case 
                if (i == input.Length - 1 && (int)(input[0]) == 45)
                {
                    result = result * -1;
                }
                // ascii '0':48 , '1':49 ...
                else
                {
                    result += (input[input.Length - 1 - i] - 48) * Convert.ToInt32(System.Math.Pow(10, i));
                }
            }
            Console.WriteLine(result);
        }

- ante5273 January 22, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static void Main()
    {
       string num = "123456";
       int intstrlength = num.Length -1;
       int base1 =1;
       int newint=0;
       for (int i=intstrlength; i >=0; i--)
       {
          newint = newint + num[i]*base1;
          base1 = base1 *10;
       }
       
       Console.WriteLine("string {0} = int {1}", num,newint);
    }

- Anonymous February 22, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

String s="45001280444010454000";
long num=0;
int temp=0;
int length=s.length();
int j=0;

for(int i=length-1;i>=0;i--)
{
temp=Integer.parseInt(String.valueOf(s.charAt(i)));
num+=temp*Math.pow(10,j);
j++;
}

System.out.println(num);

- MrWayne May 12, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

static void ConvertStringToInt(string myString)
{
int returnInt = 0;
int base1 = 1;

for (int i = myString.Length-1; i >=0; i--)
{
returnInt = returnInt + ((myString[i]-48) * base1);
base1 = base1 * 10;
}
Console.WriteLine(returnInt);
} static void ConvertStringToInt(string myString)
{
int returnInt = 0;
int base1 = 1;

for (int i = myString.Length-1; i >=0; i--)
{
returnInt = returnInt + ((myString[i]-48) * base1);
base1 = base1 * 10;
}
Console.WriteLine(returnInt);
}

- zawn589 April 04, 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