Microsoft Interview Question
Software Engineer in TestsCountry: United States
For <<, >>, it works like the following:
<<X
1.Reverse the whole string first.
2.Reverse the first X substr.
3.Reverse the last length-X substr.
For example:
Microsoft << 2:
1. tfosorciM
2. First 2 chars, ftosorciM
3. Rest substr, ftMicroso;
The >>X operation works the same way except the reverse the Length-X chars first and than X chars.
public class Oper
{
...
public string Value { get; private set; }
}
public static string operator <<(Oper lh, int rh)
{
...
int len = lh.Value.Length - rh;
return lh.Value.Substring(len) + lh.Value.Substring(0, len);
}
Oper x = new Oper("Microsoft");
string t = x << 2;
output = ftMicroso
Being a fairly easy question overall, in this case, I think the examiner would focus more on technical aspects. E.g. did you cover corner case, or NULL string, or syntax for overloading an operator
<< or >> can be implemented using any of the two approaches mentioned above:
a) Reverse entire string and then reverse parts of it
b) Get a relevant substring at starting pos and append remaning string. Would require extra space
= can be implemented using a simple strncpy or memcpy
== is strncmp
A sample for << using C#
public static string operator <<(Operator op, int num)
{
int len;
if (string.IsNullOrWhiteSpace(op.Str) || num >= op.Str.Length)
{
len = 0;
}
else
{
len = op.Str.Length - num;
}
return op.Str.Substring(len) + op.Str.Substring(0, len);
}
public class Operator
{
public string Str { get; set; }
}
Python solution
import sys
class String(object):
def __init__(self, string):
if string is not None:
self.strlen = len(string)
self.string = list(string)
self.count = 0
else:
self.string = None
def __lshift__(self, expected):
if (expected < 0 or
expected > sys.maxint or
type(expected) != int):
return 'Invalid expected value passed'
elif expected == 0:
return self.string
elif self.string is None:
return None
elif self.strlen in [1,0]:
return ''.join(self.string)
while self.count != expected:
prev = self.string[self.strlen-1]
for i in range(self.strlen-2, -1, -1):
next = self.string[i]
self.string[i] = prev
prev = next
else:
self.string[self.strlen-1] = prev
self.count += 1
return ''.join(self.string)
def __rshift__(self, expected):
if (expected < 0 or
expected > sys.maxint or
type(expected) != int):
return 'Invalid expected value passed'
elif expected == 0:
return self.string
elif self.string is None:
return None
elif self.strlen in [1,0]:
return ''.join(self.string)
while self.count != expected:
prev = self.string[0]
for i in range(1, self.strlen):
next = self.string[i]
self.string[i] = prev
prev = next
else:
self.string[0] = prev
self.count += 1
return ''.join(self.string)
print String('abcb') >> 1
functionality for operator << can be written as in C++
rest three operators follow in similar fashion
- jitendra.theta April 22, 2014