Linkedin Interview Question for Developer Program Engineers


Country: United States
Interview Type: Phone Interview




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

//This method uses the regex to check for the number.
public boolean isNumber(String str) {
	if(str==null) return false;
	return str.split("(^-)?\\d+(\\.)*\\d*").length == 0;
}
/*Most obvious way to inspect each character and check
1. Each character is number or '.' or '-'
2. There has to be only '.'
3. '-' has to appear first
Instead I chose the regex way
*/

- naren November 11, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

//Slight change for the regex 
//from the previous version.'?' for the dot instead of '*'

public boolean isNumber(String str) {
	if(str==null) return false;
	return str.split("(^-)?\\d+(\\.)?\\d*").length == 0;
}

- naren November 11, 2014 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

First regex is correct one..

- Mac December 07, 2014 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

This is correct one "(^-)?\\d+(\\.)?\\d*"

- Mac December 07, 2014 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

str.split("-?\\d+(\\.\\d+)?").length == 0

- zahidbuet106 November 03, 2015 | Flag
Comment hidden because of low score. Click to expand.
1
of 1 vote

A quick way. Let the c++ standard library make the decision.

#include <sstream>
#include <iostream>
#include <string>

void check_if_number(std::string theString)
{
  std::stringstream ss;
  ss << theString;
  ss.exceptions(std::ios::failbit | std::ios::badbit);
  try{
    int theInt;
    ss >> theInt;
    std::cout << theInt << std::endl;
  }
  catch (...)
  {
    std::cout << "not an integer!" << std::endl;
  }
}

- ahj November 11, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
1
of 1 vote

The general solution would be to check each char in turn
and report the first char that makes the string a non number.
There are some exceptions to watch out for:
The 1st char can be '-'
First occurence of '.' denotes a decimal. Subsequent
occurences mean that string is not a number

- puneet.sohi November 11, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Here is a small implementation:

bool isNumber(String s){
	if (s.length() == 0)
		return false;
	int i=0;
char c
	bool dot_flag = false; 
	is_number_flag = true;

	if (s[i] == '-')
		i++;

	while( i < s.lenght() && is_number_flag ==true ){
		c = s[i];		
		if (c >= '0' && c<= '9')
			i++;

		else if (c == '.'){
			if (dot_flag  == false)
				dot_flag = true;
			else 
				is_number_flag = false;
		}


		else
			is_number_flag  = false;
	

	}

if (is_number_flag == false)
	return false;
else
return true;

- puneet.sohi November 11, 2014 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

else if (c == '.'){
			if (dot_flag  == false)
				dot_flag = true;
			else 
				is_number_flag = false;
		}

missing i++

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

public boolean isNumber(String str) {
	if(str==null) return false;
	
	 String pattern = "^(-)?[0-9]+(\\.)?[0-9]+$";
     Pattern r = Pattern.compile(pattern);
     Matcher m = r.matcher(str);
     if (m.find( )) {
        return true;
     } else {
        return false;
     }
}

- Another way to do this November 11, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

can you explain what is ^(-)?[0-9]+(\\.)?[0-9]+$

- mikky November 11, 2014 | Flag
Comment hidden because of low score. Click to expand.
3
of 3 votes

It is a regular expression which means:
^ beginning of the string
(-)? the hyphen appear one or no times
[0-9]+ there are one or more digits sequentially
(\\.)? the period appears one or no times (\ is the escape character for the .)
[0-9]+ there are one or more digits sequentially
$ end of the string

- grekogecko November 12, 2014 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class TestRegex extends TestCase {

	@Test
	public void testNum() {
		String regex = "^(\\+|-)?[0-9]*(\\.)?[0-9]*$";
		Pattern p = Pattern.compile(regex);
		assertTrue (p.matcher("-123.123").matches());
		assertTrue (p.matcher("123.123").matches());
		assertTrue (p.matcher("+123.123").matches());
		assertFalse (p.matcher("+123s123").matches());
		assertTrue (p.matcher(".123").matches());
		assertTrue (p.matcher("0.123").matches());
		assertTrue (p.matcher("0.").matches());
		assertTrue (p.matcher(".0").matches());
		assertTrue (p.matcher(".10").matches());
		assertTrue (p.matcher(".").matches());
	}

}

- Herve.Yuancheng November 12, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

using System;
public class LetCompilerDoTheJob
{
    static void Main(string[] args)
    {
        string JustBringIt = "0.0";
        if (JustBringIt == "0.0")
        {
            //string is a number
        }
        else
        {
            double res = double.MinValue;
            double.TryParse(JustBringIt, out res);
            if (res == 0.0)
            {
                //Not a number
            }
            else
            {
                //A number
            }
        }
    }
}

- JustSteppedIn November 12, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

/**
	 * Checks for positive, negative and real numbers
	 * 
	 * @param input
	 *            The given string
	 * @return true if valid number, false if invalid
	 */
	public static boolean isValidNumber(String input) {
		if (null == input || input.isEmpty()) {
			return false;
		}
		int startIndex = 0;
		if (input.charAt(0) == '-' || input.charAt(0) == '+') {
			startIndex = 1;
		}
		boolean hasDotEncountered = false;
		for (; startIndex < input.length(); startIndex++) {
			if (isDigit(input.charAt(startIndex))) {
				continue;
			} else if (input.charAt(startIndex) == '.') {
				if (hasDotEncountered) {
					return false;
				} else {
					if (startIndex > 0 && isDigit(input.charAt(startIndex - 1)) && (startIndex + 1) < input.length()
							&& isDigit(input.charAt(startIndex + 1))) {
						hasDotEncountered = true;
						continue;
					} else {
						return false;
					}
				}
			} else {
				return false;
			}
		}
		return true;
	}

	private static boolean isDigit(char c) {

		if (c >= '0' && c <= '9') {
			return true;
		} else {
			return false;
		}
	}

- Anonymous November 12, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

this will cause
"-.1" to pass the isNumber.

here is my approach i did it independently of yours, quite similar though

public boolean isANumber(String input) {
        if (null == input || input.isEmpty()) {
            return false;
        } else if (input.length() == 1) {
            return isADigit(input.charAt(0));
        }
        char first = input.charAt(0);
        if ((first == '-' && isADigit(input.charAt(1))) || isADigit(first)) {
            boolean decimalFound = false;
            int i = 1;
            while (i < input.length()
                    && (isADigit(input.charAt(i))
                    || (input.charAt(i) == '.'
                    && !decimalFound))) {
                decimalFound = decimalFound ^ input.charAt(i) == '.';
                i++;
            }
            if (i == input.length() && input.charAt(i-1) != '.') {
                return true;
            }
        }
        return false;
    }

    private boolean isADigit(char input) {
        return (input >= '0' && input <= '9');
    }

- joy November 14, 2014 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

public boolean isANumber(String input) {
        if (null == input || input.isEmpty()) {
            return false;
        } else if (input.length() == 1) {
            return isADigit(input.charAt(0));
        }
        char first = input.charAt(0);
        if ((first == '-' && isADigit(input.charAt(1))) || isADigit(first)) {
            boolean decimalFound = false;
            int i = 1;
            while (i < input.length()
                    && (isADigit(input.charAt(i))
                    || (input.charAt(i) == '.'
                    && !decimalFound))) {
                decimalFound = decimalFound ^ input.charAt(i) == '.';
                i++;
            }
            if (i == input.length() && input.charAt(i-1) != '.') {
                return true;
            }
        }
        return false;
    }

    private boolean isADigit(char input) {
        return (input >= '0' && input <= '9');

}

- byteattack November 14, 2014 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

Defining a number as the following structure:

[optional '-'][any number of #s][optional '.' [any number of #s] ]

public static boolean isNumber(String str){
	//handle the easy cases
	if(str == null){
		throw new NullPointerException("\"str\" may not be null");
	}
	if(str.isEmpty()){
		return false;
	}

	char[] chars = str.toCharArray();
	int charIndex = 0;
	//allow optional '-'
	if(chars[charIndex] == '-'){
		charIndex++;
	}
	//handle unlimited amount of numbers and single '.'
	boolean noDecimalPt = true;
	while(charIndex < chars.length){
		char c = chars[charIndex];
		//if the char is not a digit
		if(!isNumChar(c){
			//it may be a '.' one time
			if(c == '.' && noDecimalPt){
				noDecimalPt = false;
			}
			//otherwise this is a bad character
			else{
				return false;
			}
		}
		charIndex++;
	}
	return true;
}

public static boolean isNumChar(char c){
	if(c < '0' || c > '9'){
		return false;
	}
	return true;
}

- zortlord November 12, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Here is the java code:

public boolean isNumber(String s)
{
char c='.';
char d='-';
for (int i=0; i < s.length(); i++)
{
if (s.charAt(i)!=c && s.charAt(i)!=d)
{
boolean result=Character.isDigit(s.charAt(i));
if (!result)
return false;
}
}
return true;
}

- Anonymous November 16, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Here is the java code:

public boolean isNumber(String s)
{
char c='.';
char d='-';
for (int i=0; i < s.length(); i++)
{
if (s.charAt(i)!=c && s.charAt(i)!=d)
{
boolean result=Character.isDigit(s.charAt(i));
if (!result)
return false;
}
}
return true;
}

- Anonymous November 16, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

/**
 * 
 * Assumption :
 * +123.40 , where + sign appears before the number is valid
 * 146. , where no digits after point is not a valid number
 * 
 * For a string to be a number, it should be of the format
 * 
 * [0 or 1 occurrence of either + or -]
 * followed by
 * [at least one occurrence of digits between 0 to 9]
 * followed by
 * [0 or 1 occurrence of .]
 * followed by
 * [at least one occurrence of numbers between 0 to 9]
 * 
 * [+|-] means either + or -
 * [+|-]? means either + or - should occur once or not at all
 * \d means a digit. To escape the backslash, you need \\d
 * \\d+ means a digit should occur atleast once
 * .? means that a should occur or not at all
 *  \\d+ means a digit should occur atleast once
 */
public class IsStringANumber {
	
	public static boolean isANumber(String str) {
		
		if (str == null || str.trim().equals(""))
			return false;
		
		return Pattern.matches("[+|-]?\\d+.?\\d+", str);
	}
}

- Sean November 24, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Using python and little bit of help from this forum:

import re

def Check_Number(Str):

	pattern = "^(-)?[0-9]+(\\.)?[0-9]+$"
	
	if re.search(pattern,Str):
		return True
	else:
		return False
		
print Check_Number("-3.3425")

But the problem is that if we pass an integer number, this will return False.

- satishsagar83 November 25, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

bool is_number(string &str) {
	int len = str.size();
	int count = 0;
	bool one_dot = false;
	bool one_digit = false;
	if(len == 0) {
		return 0;
	}
	for(int i = 0; i < len; ++i) {
		if(i == 0 && str[i] == '-') {
			count++;
		}
		else if(str[i] == '.' && one_dot == false
							&& one_digit == true) {
			count++;
			one_dot = true;
		}
		else if(str[i] >= '0' && str[i] <= '9') {
			one_digit = true;
			count++;
		}
		else {
			return false;
		}
	}
	if(count == len && one_digit == true) {
		return true;
	}
	return false;
}

- neham November 26, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static boolean checkForNumber2(String input) {
		if(input == null) return false;
		try{
			Double.parseDouble(input);
			return true;
		} catch(NumberFormatException e) {
			return false;
		}
	}

- Mac December 07, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class Check {
	public static void main(String[] args) throws IOException {
		BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
		String s;
		double n;
		s=br.readLine();
		try{
			n=Double.parseDouble(s);
			System.out.println("ok! its a number "+n);
		}catch(NumberFormatException e){
			System.out.println("well! its not a number");
		}
	}

}

- Kundan Kumar December 13, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static boolean ifNumber(char[] arr,int index,boolean hasEncounteredDecimal){
if(index>=arr.length) return true;

if(isDigit(arr[index])|| (index==0 && (arr[index]=='-'|| arr[index]=='+'))){
return ifNumber(arr, index+1,hasEncounteredDecimal);
}
else if(arr[index]=='.'){
if(hasEncounteredDecimal){
return false;
}
else if(index>0 && index<arr.length-1 && isDigit(arr[index-1]) && isDigit(arr[index+1])){
hasEncounteredDecimal = true;
return ifNumber(arr, index+2, hasEncounteredDecimal);
}
else{
return false;
}
}
else{
return false;
}

}

public static boolean isDigit(char value){
if(value>='0' && value<='9'){
return true;
}
return false;
}

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

public static boolean ifNumber(char[] arr,int index,boolean hasEncounteredDecimal){
		if(index>=arr.length) return true;
		
		if(isDigit(arr[index])|| (index==0 && (arr[index]=='-'|| arr[index]=='+'))){
			return ifNumber(arr, index+1,hasEncounteredDecimal);
		}
		else if(arr[index]=='.'){
			if(hasEncounteredDecimal){
				return false;
			}
			else if(index>0 && index<arr.length-1 && isDigit(arr[index-1]) && isDigit(arr[index+1])){
				hasEncounteredDecimal = true;
				return ifNumber(arr, index+2, hasEncounteredDecimal);
			}
			else{
				return false;
			}
		}
		else{
			return false;
		}
		
	}
	
	public static boolean isDigit(char value){
		if(value>='0' && value<='9'){
			return true;
		}
		return false;
	}

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

public boolean isNumber(String s){
				
		boolean sign = false;
		boolean dot = false;

		if(s == null || s.isEmpty()){
			return false;
		}

		for(int i = 0; i < s.length(); i++){

			if(sign && (s.charAt(i) == '-' || s.charAt(i) == '+')){
				return false;
			}

			if(dot && s.charAt(i) == '.'){
				return false;
			}
			
			if(i == 0 && (s.charAt(i) == '-' || s.charAt(i) == '+')){
				sign = true;
				continue;
			}
			
			if(!dot && s.charAt(i) == '.'){
				dot = true;
				continue;
			}

			if((s.charAt(i) < '0' || s.charAt(i) > '9')){							 	   
				return false;				  	
			}

		}
		return true;
	}

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

bool IsNumber(string s)
{
	int N = s.length();
	bool metDot = false;
	for (int i=0; i<N; i++)
	{
		char c = s[i];
		if (c < '0' || c > '9') //Not digit
		{
			if (i == 0 && (c == '-' || c == '+'))
				continue;

			if (i > 0 && i < N-1 && c == '.' && !metDot)
			{
				metDot = true;
				continue;
			}

			return false;
		}
	}

	return true;

}

- pavel.kogan January 10, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

A lot of the answer is not working, here are some examples:
"0011"
"1."
"1.0000"
(^-)?[1-9]+[0-9]*(\\.[0-9]*[1-9]+)

Or the interviewer may consider them as valid

- Gordon January 30, 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