Microsoft Interview Question


Country: United States




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

this function only does validation on IP4 addresses

public static bool IsValidIP(String inputString)
	{
		if (inputString == null)
		{
			return false;
		}
		
		string[] numbers = inputString.Split('.');
		if (numbers.Length != 4)
		{
			return false;
		}
		
		try
		{
			foreach (string number in numbers)
			{
				byte byteValue = Byte.Parse(number);
			}
		}
		catch(Exception e)
		{
			return false;
		}
		
		return true;
	}

- akiremi January 23, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
1
of 1 vote

byte value itself is between 0 to 255

- akiremi January 23, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

0000.0000.0000.0000 is valid ip ?

- shishir January 23, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

The below line should be

string[] numbers = inputString.split("\\.");

Else can use the:

StringTokenizer stringTokenizer = new StringTokenizer( ip, "." ); 
	while ( stringTokenizer.hasMoreTokens() ) { 
		byte byteValue = Byte.parseByte(stringTokenizer.nextToken()) ;
	}

- R@M3$H.N January 23, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

try this,

IsValidIp("127.-0,0000, 1)

- dangled January 23, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

public static bool IsValidIp(string address)
        {
            int dotCount = 0;
            int returnValue = 0;
            var isValid = true;
            var total = 0;

            foreach (var digit in address)
            {
                if ((digit < '0' || digit > '9') && digit != '.' || !isValid) 
                    return false;

                if (digit == '.')
                {
                    total += returnValue;
                    returnValue = 0;
                    dotCount++;
                    continue;
                }

                returnValue = (returnValue * 10) + (digit - '0');
                isValid &= returnValue < 256;
            }

            isValid &= (total != 0) && (total <= (255 * 4)) && dotCount == 3;

            return isValid;
        }

- Asiful Haque Mahfuze February 10, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

Using the inet_pton - which returns -1 on failure, and supports both the IPv4 and future IPv6 addresses

#include <arpa/inet.h>
bool isValidIP(char * ipAddr)
{
    struct sockaddr_in socAddr;
    return ( inet_pton(AF_INET, ipAddr, &(socAddr.sin_addr)) != 0 ) ;
}

Using Regular Expressions for IPV4:

package sample;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class IPAddrValidator {
	
	public boolean validate(final String ip){		  
		  matcher = pattern.matcher(ip);
		  return matcher.matches();	    	    
	    }

	public IPAddrValidator() {
		pattern = Pattern.compile(IP_ADDRESS_PATTERN);
	}

	private Pattern pattern;
    private Matcher matcher;
 
    private static final String IP_ADDRESS_PATTERN = 
		"^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
		"([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
		"([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
		"([01]?\\d\\d?|2[0-4]\\d|25[0-5])$";
 
    
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String ip = new String ("1.1.1.1") ;
		IPAddrValidator ipValidator = new IPAddrValidator();
		System.out.println("IP Address = "+ ip + " is " + ipValidator.validate(ip) );
		System.out.println("IP Address = "+ "127.0.0.1" + " is " + ipValidator.validate("127.0.0.1") );
		System.out.println("IP Address = "+ "10.10" + " is " + ipValidator.validate("10.10") );
	}
}

- R@M3$H.N January 23, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

String IP="129.777.0.0";
		boolean isValid=true;
		String ip[]=IP.split("\\.");
		if(ip.length>4)
			isValid=false;
		else
		{
			for(int i=0;i<ip.length;i++)
			{
				try
				{
					int n=Integer.parseInt(ip[i]);
					if(n<0||n>255)
					{	
						isValid=false;
						break;
					}
				}
				catch(NumberFormatException e)
				{
					isValid=false;
				}
			}
			if(isValid)
				System.out.println("valid IP");
			else
				System.out.println("Inavalid IP");
		}

- Anonymous January 23, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

String ip="129.1.0.0";
boolean isValid=true;
String ipa[]=new String[4];
//max size of ip is 15
if(ip.length()>15)
	isValid=false;
else
{
	int i=ip.indexOf('.');
int j=ip.lastIndexOf('.');
ipa[0]=ip.substring(0,i);
ipa[3]=ip.substring(j+1,ip.length());
String mid=ip.substring(i+1,j);
ipa[1]=mid.substring(0,mid.indexOf('.'));
ipa[2]=mid.substring(mid.indexOf('.')+1,mid.length());
	for(i=0;i<4;i++)
	{
		try
		{
			int n=Integer.parseInt(ipa[i]);
			if(n<0||n>255)
			{	
				isValid=false;
				break;
			}
		}
		catch(NumberFormatException e)
		{
			isValid=false;
		}
	}
}
if(isValid)
	System.out.println("valid IP");
else
	System.out.println("Inavalid IP");

- madhumati hosamani January 23, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

In C++:

bool isValidIp(const std::string &ip)
{
	int dotidx[3];
	int idx, len = ip.length();
	int currdot = 0;

	for (idx = 0; idx < len; ++idx) {
		if (ip[idx] == '.') {
			// string has more than 3 dots
			if (currdot > 2) {
				return false;
			}

			dotidx[currdot] = idx+1;
			++currdot;
		}
		else if (ip[idx] < '0' or ip[idx] > '9') {
			// non numeric
			return false;
		}
	}

	// less than 3 dots
	if (currdot != 3)
		return false;

	int i;

	// empty bytes
	for (i = 0; i < 2; ++i) {
		if (dotidx[i]+1 == dotidx[i+1]) {
			return false;
		}
	}
	if (dotidx[2] >= len) {
		return false;
	}

	for (i = 0; i < 3; ++i) {
		std::string byte;
		if (i < 2) {
			byte = ip.substr(dotidx[i], dotidx[i+1]-dotidx[i]-1);
		}
		else {
			byte = ip.substr(dotidx[i], len-dotidx[i]);
		}
		int decimal = atoi(byte.c_str());
		if (decimal > 255) {
			return false;
		}
	}

	return true;
}

- Victor January 24, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.
  (25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.
  (25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.
  (25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b

- m@}{ January 24, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

I assume that making use of regular expressions, Socket API and system parse methods is a bit of overhead. At least, it's not what interviewers usually expect. Here's the code that gets the job done with one simple linear scan.

namespace CareerCup
{
    public class ValidIpAddress
    {
        public bool IsValidIpAddress(string input)
        {
            if (string.IsNullOrEmpty(input) || input.Length > 15)
            {
                return false;
            }

            int lastOctet = 0;
            bool hasLeadingZeros = false;
            int octetsCount = 0;
            for (int i = 0; i < input.Length; ++i)
            {
                bool checkLastOctet = false;
                char current = input[i];
                if (char.IsDigit(current))
                {
                    lastOctet = lastOctet * 10 + (input[i] - '0');
                    if (lastOctet == 0)
                    {
                        hasLeadingZeros = true;
                    }
                    if (i == input.Length - 1)
                    {
                        checkLastOctet = true;
                    }
                }
                else if (current == '.')
                {
                    checkLastOctet = true;
                }
                else
                {
                    return false;
                }

                if (checkLastOctet)
                {
                    if (lastOctet > 255 || (lastOctet != 0 && hasLeadingZeros))
                    {
                        return false;
                    }
                    lastOctet = 0;
                    hasLeadingZeros = false;
                    octetsCount++;
                }
            }

            return octetsCount == 4;
        }
    }
}

- stanislav.khalash January 24, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static boolean isValidIP(String s) {
		String[] _ipArray = s.split("\\.");
		if (_ipArray.length != 4)
			return false;
		else {
			for (String string : _ipArray) {
				
				try{
					if (!(Integer.parseInt(string) >= 0 || Integer.parseInt(string) <= 255))
						return false;
				}
				catch(NumberFormatException e){
					return false;
				}
				
			}
		}
		return true;
	}

- ankit.vader February 02, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static bool IsValidIp(string address)
        {
            int dotCount = 0;
            int returnValue = 0;
            var isValid = true;
            var total = 0;

            foreach (var digit in address)
            {
                if ((digit < '0' || digit > '9') && digit != '.' || !isValid) 
                    return false;

                if (digit == '.')
                {
                    total += returnValue;
                    returnValue = 0;
                    dotCount++;
                    continue;
                }

                returnValue = (returnValue * 10) + (digit - '0');
                isValid &= returnValue < 256;
            }

            isValid &= (total != 0) && (total <= (255 * 4)) && dotCount == 3;

            return isValid;
        }

- Asiful Haque Mahfuze February 10, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static boolean isValidIp(String s){
		if(s==null || s.length()==0||s.length()>15) return false;
		for(int i = 0,num=0,numDots=0;i<s.length();i++){
			char c = s.charAt(i);
			if(c=='.'){
				if(++numDots>3 || num>255) return false;
				num = 0;
			}else{
				int digit = c-'0';
				if(digit<0||digit>9)return false;
				num*=10;
				num+=digit;
				if(num>255)return false;
			}
		}
		return true;
	}

- srcnaks March 02, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include <iostream>
#include <string.h>
using namespace std;

bool isValid(const char *str) {

	int len = strlen(str);
	bool valid = true;
	int numCount = 0, dotCount = 0;

	for(int i = 0; i < len;) {
		
		int j = i;
		
		int num = 0;

		if(numCount == 4) {
			valid = false;
			break;
		}

		for(; j < len; ++j) {
			if(str[j] < '0' || str[j] > '9')
				break;
			num = num * 10 + (str[j] - '0');
		}
		if((j == i) || (num < 0) || (num > 255)) {
			valid = false;
			break;
		}
		
		numCount++;
		
		if(j < len) {
			if((str[j] != '.') || ((str[j] == '.') && (dotCount == 3))) {
				valid = false;
				break;
			}
			else 
				dotCount++;
			j++;
		}
		
		i = j;
	}
	if((numCount != 4) && (dotCount != 3))
		valid = false;
	return valid;
}

int main() {
	cout << boolalpha << isValid("255...") << endl;
	cout << boolalpha << isValid("255.255.255. 255") << endl;
	cout << boolalpha << isValid(".") << endl;
	cout << boolalpha << isValid(".255.255.t") << endl;
	return 0;
}

- rishab99999 April 06, 2015 | 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