Microsoft Interview Question
Software Engineer / DevelopersCountry: United States
Interview Type: In-Person
Just FYI, most interviewers will expect you to do a static test of your code. At very least you will want to pass even and odd length palindromes and non-palindromes, plus various corner cases like empty string and single-character. Doing this, you would spot that this code does a meaningless final comparison for all odd-length palindromes (including single character input)--how can a character not be equal to itself? You should also provide a type for inputStr; You never know if your interviewer might try to type it in verbatim and compile it, or what they consider excusable.
#include<iostream>
#include<string.h>
using namespace std;
int main()
{
string str;
cin>>str;
int i=0,j=str.length()-1;
int k=1;
while(i<=j)
{
if(str[i]==str[j])
{
i++;
j--;
}
else
{
k=0;
break;
}
}
if(k==0)
cout<<"Given string is not a palindrome";
else
cout<<"Given string is palindrome";
return 0;
}
While your main() function is technically a function which detects a palindrome, you will be expected to understand that you're being asked for a utility function that takes some manner of string as an argument and returns a boolean or equivalent enum value.
Secondly, the <= in the while loop condition results in one extra iteration of the loop for odd-length strings, wherein you check the middle character against itself unnecessarily.
Lastly, once converted to a utility function there will be no need for the allocation of k, or the if-then after the loop, since you'll exit with a return false where you have the k=0, or return true after the loop. Also, allocating an int where only a bool is needed is poor form, since an int can be much larger than a bool on some systems (memory wasted). Using appropriate types makes for better portability and readability.
public class checkIfPalindrome
{
public static void main(String[] args)
{
System.out.println(check("teet"));
}
static boolean check(String str)
{
if(str.length()==0) return false;
for(int i=0;i<str.length()/2;i++)
{
if(str.charAt(i)!=str.charAt(str.length()-1-i))
return false;
}
return true;
}
}
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include <string>
using namespace std;
bool isPalindrome(string str)
{
int len=str.length();
for(int i=0;i<len;i++){
if(str[i]!=str[len-1-i])
return false;
}
return true;
}
int main(int argc, char* argv[])
{
cout << isPalindrome(argv[1]) << endl;
return 0;
}
string mainString = "sasas";
char[] mainArr = mainString.ToCharArray();
StringBuilder sb = new StringBuilder();
for (int i = mainArr.Length - 1; i >= 0; i--)
{
sb.Append(mainArr[i]);
}
if (mainString == sb.ToString())
Console.WriteLine("Palindrome");
else
Console.WriteLine(" no Palindrome");
Console.Read();
C# ( for MS :D )
- john madden john madden john madden October 02, 2014