Linkedin Interview Question for Front-end Software Engineers


Country: United States
Interview Type: Phone Interview




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

public bool isNumber(String s) {
	bool signOccured = false;
	bool dotOccured = false;
	bool started = false;

	s = s.trim();

	for(char c : s.toCharArray()) {
		switch (c) {
			case '+', '-':
				if (started || signOccured || dotOccured) {
					return false;
				} else {
					signOccured = true;
				}
				break;
			case '0'-'9':
				started = true;
				break;
			case '.':
				if (dotOccured) {
					return false;
				} else {
					dotOccured = true;
				}
			default:
				return false;
		}
	}
	return true;	
}

- Bharat Kumar Arya January 13, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Seem like you missed one case where the '.' (dot) is at the end of the string.
Example "476." which should ideally return false.

- blurred July 22, 2015 | Flag
Comment hidden because of low score. Click to expand.
2
of 2 vote

This is my C# solution to the problem, unfortunately I couldn't be able to write it on time due to my nerves! Best of luck guys!

public static bool IsNumber(string number)
{
      int n = number.Length, dots = 0;
      if (number[0] == '.' || number[n - 1] == '.' || number[n - 1] == '-')
           return false;
      if ((number[0] < 48 || number[0] > 57) && number[0] != '-')
           return false;
      for (var i = 1; i < n; i++)
      {
            if (dots > 1)
                return false;
            if (number[i] < 48 || number[i] > 57)
            {
                 if (number[i] == '.')
                 {
                      if (i == 1 && number[0] == '-')
                          return false;
                      else
                          dots++;
                  }
                  else
                       return false;
            }
      }
      return true;
}

- Raul Rivero January 13, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

int
is_num(char *ch)
{
	char c = *ch;
	return ((c >= '0') && (c <= '9'));
}

int
IsNumber(char *str)
{
	int is_number = 1;

	assert(str);

	while (*str != '\0') {
		if (is_num(str) == 0) {
			is_number=0;
			break;
		} else {
			str++;
		}
	}

	if (is_number) {
		printf("string is a number.\n");
	} else {
		printf("string is NOT a number.\n");
	}

	return (is_number);
}

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

public static boolean isNumber(String str)
	{
		char[] charArray=str.toCharArray(); /*in java internally String is maintained as charecter
		array, so atleast we have to use this function*/

		char strt='0';
	char end='9';

	for(char ch: charArray)
	{
		if(ch<strt || ch> end)
			return false;
	}
	return true;
	}

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

iterate each character.
have a flag for if dot occurred
first character can be - or 0-9
all other characters can be 0-9, and dot if not flag

- sean January 13, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 4 vote

Lets assume that string is represented as a sequence of ASCII chars. Hence there exist mapping char -> int. Next you know that in this preresentations characters 0-9 is a continuous sequence. Given a string, for each of its character check if it is a character between '0' and '9'.

A sample code in java is shown below:

public boolean isNumber(String s) {
	for (char c : S)
		if (c < '0' || c > '9')		return false;

	return true;
}

Not sure how it would work for Unicode but I think it should. I the number was negative, just check for char '-' at position 0.

- autoboli January 13, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Awesome! So simple....

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

I forgot to put some test cases like:

incorrect numbers: "-.15", "12.3-", "4fe", ".15", "15.", "15-", "1-5" // return false
correct numbers: "154", "-23", "15.36", "-1.25" // return true

- Raul Rivero January 13, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

In some languages like C# above mentioned condition fails as 'c' returns ASCII code not the actual number in the above statement.

So we should use the condition as

public boolean isNumber(String SrcStr)
{
	foreach (char c in SrcStr)
	{
		if (c-'0' < '0' || c-'0' > '9')		
		{
			return false;
		}
	}
	return true;
}

- Srigopal Chitrapu January 14, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

* ad folats: you are right, it handles only positive integers, the code was to demonstrate the approach.
* ad C#: First, it is a java code, second, as you said, I am also comparing ASCII codes and take advantage of the fact that digit characers follows each other in a single sequence in ASCII representation. Do you agree?

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

this code doesn't work for double digits, but that problem also has easy solution

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

It's very very simple ! why ?

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

Because I was very nervous and tense, I was under pressure and got stuck with that simple problem. I've done interviews before and this one was the worst.

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

public static boolean isNumber(String input) {
		for (int i = 0; i < input.length(); i++) {
			int c = input.charAt(i);
			System.out.println(c);
			if (!(c >= 48 && c <= 57)) {
				return false;
			}
		}
		return true;
	}

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

Please give some feedback on this code. Thanks!

public static boolean  isNumber(String input)
{
	boolean  dotFlag=true;   // to check dot occurs only once for floating numbers

	for(int k=0; k< input.length(); k++)
	{
		final char c= input.charAt(k);
		if ( ( c == '.' ) && (k != input.length() -1 ) && dotFlag ) // Dot can appear only once and not at last position 		       
		{
			dotFlag=false;
			continue;
		}
		if( ( (c == '-')  || ( c== '+' ) )&&  k == 0 ) continue;    // Negative/Postive sign can appear only at beginning
		if ( (c >= '0')  &&  (c <= '9') ) continue; 
		return false;
	}
return true;
}

- Glad Born January 14, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

If they ask this you're probably meant to ask to specify what kind of numbers they want. If it's integers, the solutions is simple:

def isNumber(num):
	return all(x in ['1','2','3','4','5','6','7','8','9','0'] for x in num)

If they also want numbers which have decimal part in them, you'll have to check for the separator, which is usually a dot but varies, eg comma is quite common too.

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

bool check(string s){
    int i = 0 ;
    while(s[i] != '\0'){
        if(( s[i] < 48 or s[i] > 57) ) {
             return false;
        }else{
           i++;
        }
    }
    return true;
}

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

Can't this easily be done with regex?

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

Solution with regex in javascript:

(/^-?\d+.?\d+$/).test("-121.21")

- Vic January 24, 2015 | Flag
Comment hidden because of low score. Click to expand.
1
of 1 vote

As noted - "without using built in functions". The point here is to actually write an algorithm to do it yourself, not to use the framework. Since his original solution was C#, he could have just written "return double.TryPrase(num, out result);" if framework calls were allowed.

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

Your regex will not work for negative number e.g -4
correct regex is ("^-?\d*.?\d*$")

- Sunny December 07, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

Using Javascript:

function isInteger(x){
return (x^0) == x;
}
console.log(isInteger('555'));

- srinivasan February 13, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

function isInteger(x){
    return (x^0) == x;
}
console.log(isInteger('555'));

- srinivasan February 13, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

def self.isNumber?(value)
		return false if value.nil? or value.empty?
		return value =~ /^((\d+)?[\.,]?(\d+)?)+$/ ? true : false
	end

- rahul February 16, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

/* Check if the variable is Integer */
function isNumber(num){
return +num === num;
}




/* Check if the variable is Integer */
function isInteger(x){
return (x^0) == x;
}

- Mouli February 27, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

class CheckFormat{

    public static boolean isNumber(String input){

        char[] arr = input.toCharArray();
        boolean isNumber = true;
        boolean isDotted = false;

        for(int n = 0; n < arr.length; n++){
            if(arr[n] == '-' && n == 0)
                continue;
            else if(((arr[n] - '0') >= 0) && ((arr[n]-'0') <= 9))
                continue;
            else if(arr[n] == '.' && !isDotted){
                isDotted = true;
                continue;
            }
            else{
                isNumber = false;
                break;
            }
        }
        if(isDotted && (arr[arr.length - 1] == '.'))
            isNumber = false;

        return isNumber;
    }

}

- blurred July 22, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Here is C++ version of solution

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

bool is_sign(char c)
{
  return (c=='+' || c =='-');
}

bool is_num(char c)
{
  return (c>='0' && c<='9');
}

bool IsNumber(string num)
{
  bool hasDot = false;
  bool hasNum = false;
  for(int i = 0; i < num.length(); i++)
  {
    if (num[i] == ' ')
      continue;
    if (i ==0)
    {
      if (!is_sign(num[i]) && !is_num(num[i]))
        return false;
      hasNum = is_num(num[i]);
    } else if (num[i] == '.')
    {
      if (hasDot)
        return false;
      if (!hasNum)
        return false;
      if (i == num.length()-1)
        return false;
      hasDot =true;
    } else {
        if(!is_num(num[i]))
          return false;
        if (!hasNum)
          hasNum = true;
    }
  }
  return (hasNum);
}

- hankm2004 August 10, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

// ASCII of numbers 0-9 is 48-57, ASCII of . is 46, ASCII of - is 45, ASCII of , is 44, ASCII of + is 43
    public boolean isNumber(String str){

        if(str == null || str.isEmpty()) return false;
        boolean answer = true;

        int temp = str.charAt(0);
        if(temp >=48 && temp<57){
            answer = answer && true;
        }else if(temp==45 || temp == 43){
            answer = answer && true;
        }
        for(int i=1; i< str.length(); i++){
            temp = str.charAt(i);
            if(temp >= 48 && temp <= 57){
                answer = answer & true;
            } else if(temp == 46 || temp == 44){
                answer = answer && true;
            } else {
                answer = false;
                break;
            }
        }

        return answer;

}

- vrunda.nagpurkar October 21, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Cases considered are
System.out.println("isNumber " + lq.isNumber("0123"));
System.out.println("isNumber " + lq.isNumber("123.67"));
System.out.println("isNumber " + lq.isNumber("-8"));
System.out.println("isNumber " + lq.isNumber("-12.ab12345"));
System.out.println("isNumber " + lq.isNumber("12,345"));
System.out.println("isNumber " + lq.isNumber("+98987"));
System.out.println("isNumber " + lq.isNumber("98-987"));

- vrunda.nagpurkar October 21, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote
Could be done in js like this {{{ function isNumber(str) { {{{return !isNaN(+str);}}} } }}} - Anonymous December 16, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class Number {
    private enum State {
        INIT, SIGN, INTEGER, DOT, FRACTION
    }

    public static boolean isNumber(String str) {
        // RegEx: [+-]? [0-9]+ (\.[0-9]+)?

        State state = State.INIT;
        for (final char ch : str.trim().toCharArray()) {
            switch (state) {
            case INIT:
                if (ch == '+' || ch == '-') {
                    state = State.SIGN;
                } else if (ch >= '0' && ch <= '9') {
                    state = State.INTEGER;
                } else {
                    return false;
                }
                break;
            case SIGN:
                if (ch >= '0' && ch <= '9') {
                    state = State.INTEGER;
                } else {
                    return false;
                }
                break;
            case INTEGER:
                if (ch == '.') {
                    state = State.DOT;
                } else if (ch < '0' || ch > '9') {
                    return false;
                }
                break;
            case DOT:
                if (ch >= '0' && ch <= '9') {
                    state = State.FRACTION;
                } else {
                    return false;
                }
                break;
            case FRACTION:
                if (ch < '0' || ch > '9') {
                    return false;
                }
                break;
            }
        }

        return (state == State.INTEGER || state == State.FRACTION);
    }

    public static void main(String[] args) {
        final String str[] = { "1", "10", "0123", "-20", "+40", ";", "10.", "-", "-23.45" };
        for (final String s : str) {
            System.out.println("Test: \"" + s + "\" is" + ((Number.isNumber(s)) ? " " : " not ") + "a number");
        }
    }

}

- scgupta December 30, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Javascript:

function isNumber(str) {
  var dotFlag = false;

  for (var i=0, len=str.length; i<len; i++) {
    var c = str[i];

    // removes preceding - or +
    if (!i && c == '-' || c == '+') {
      continue;
    }

    // if dot
    if (c == '.') {
      // if already found before
      if (dotFlag) {
        return false;
      }
      // save for next time
      dotFlag = true;
    } else if (!(c < 10)) {
      return false;
    }
  }

  return true;
};

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

Exploit Javascript's coercion:

function isNumber(n){
  return n > 0 || n < 0 || n==0;
}

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

function isNumber(n){
if(+n){
return true;
}else{
return false;
}
}

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

function  isNumber( str ){
	return window.toString.call(str) === "[object Number]";
  }

- simple one October 03, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Clear java solution with custom string iterator (accepted on Leetcode):
leetcode.com/problems/valid-number/

public class Solution
{
    /** A helper class for iterating over string characters (more like a queue) */
    private static class StringIterator
    {
        private final String str;
        private int index;

        public StringIterator(String str)
        {
            this.str = str;
            this.index = -1;
        }

        /** True, if the next character is one of the characters from the string */
        public boolean checkNext(String chars)
        {
            return hasNext() && chars.indexOf(peek()) != -1;
        }

        /** True, if the next character is one of the characters from the string + skip it */
        public boolean skipNext(String chars)
        {
            if (checkNext(chars))
            {
                next();
                return true;
            }
            return false;
        }

        /** Has more characters */
        public boolean hasNext()
        {
            return index + 1 < str.length();
        }

        /** Check the next character without removing it */
        public char peek()
        {
            return str.charAt(index + 1);
        }

        /** Remove and return next character */
        public char next()
        {
            return str.charAt(++index);
        }

        /** Number of available characters */
        public int available()
        {
            return str.length() - (index + 1);
        }
    }

    private enum DigitBase
    {
        Dec,     // decimal
        Hex,     // hexadecimal
    }

    public boolean isNumber(String s)
    {
        s = s.trim();

        if (s.length() == 0) return false;

        StringIterator iter = new StringIterator(s);

        // check sign
        if (iter.skipNext("+-") && !iter.hasNext()) return false;

        // if only one char is available - it should be a digit
        if (iter.available() == 1) return isValidDigit(iter.next(), DigitBase.Dec);

        DigitBase digitBase = DigitBase.Dec; // decimal by default

        boolean hasIntegerPart = false;
        boolean hasFracPart = false;

        // check next numbers
        if (iter.skipNext("0"))
        {
            // simple zero
            if (!iter.hasNext()) return true;

            if (iter.skipNext("xX"))
            {
                if (!iter.hasNext()) return true;
                digitBase = DigitBase.Hex;
            }
            else
            {
                hasIntegerPart = true;
            }
        }

        boolean hasDecimalPoint = false;
        boolean hasExponent = false;

        // check chars one by one
        while (iter.hasNext())
        {
            char c = iter.next();

            if (c == ' ')
            {
                return false; // can't have any spaces
            }
            else if (c == '.')
            {
                // can only have a single decimal point and no exponent yet
                if (hasDecimalPoint || hasExponent || digitBase != DigitBase.Dec) return false;

                hasDecimalPoint = true;
            }
            else if (isValidDigit(c, digitBase)) // valid character for the selected base
            {
                if (hasDecimalPoint)
                {
                    hasFracPart = true; // if decimal point was found - then we have a fracture part
                }
                else if (!hasExponent)
                {
                    hasIntegerPart = true; // if exponent was not found - we have an integer part
                }
            }
            else if (oneOf(c, "eE")) // found exponent?
            {
                if (!iter.hasNext()) return false; // if no character after - invalid number

                // we should have a single exponent and at least either an integer or a fracture part
                if (hasExponent || !hasIntegerPart && !hasFracPart) return false;

                hasExponent = true;

                // an optional +/- sign
                if (iter.skipNext("-+") && !iter.hasNext()) return false;

                digitBase = DigitBase.Dec; // HACK: only expect decimal digits
            }
            else
            {
                return false; // something unexpected
            }
        }

        return true; // all good!
    }

    /** Is a valid digit for the selected base */
    private boolean isValidDigit(char c, DigitBase digitBase)
    {
        switch (digitBase)
        {
            case Hex: return c >= '0' && c <= '9' || c >= 'a' && c <= 'f' || c >= 'A' && c <= 'F';
        }
        return c >= '0' && c <= '9';
    }

    /** True is char is one of the characters from the string */
    private boolean oneOf(char c, String chars)
    {
        return chars.indexOf(c) != -1;
    }

}

- Alex Lementuev October 11, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

A clear java solution with a custom string iterator (accepted on LeetCode):

public class Solution
{
    /** A helper class for iterating over string characters (more like a queue) */
    private static class StringIterator
    {
        private final String str;
        private int index;

        public StringIterator(String str)
        {
            this.str = str;
            this.index = -1;
        }

        /** True, if the next character is one of the characters from the string */
        public boolean checkNext(String chars)
        {
            return hasNext() && chars.indexOf(peek()) != -1;
        }

        /** True, if the next character is one of the characters from the string + skip it */
        public boolean skipNext(String chars)
        {
            if (checkNext(chars))
            {
                next();
                return true;
            }
            return false;
        }

        /** Has more characters */
        public boolean hasNext()
        {
            return index + 1 < str.length();
        }

        /** Check the next character without removing it */
        public char peek()
        {
            return str.charAt(index + 1);
        }

        /** Remove and return next character */
        public char next()
        {
            return str.charAt(++index);
        }

        /** Number of available characters */
        public int available()
        {
            return str.length() - (index + 1);
        }
    }

    private enum DigitBase
    {
        Dec,     // decimal
        Hex,     // hexadecimal
    }

    public boolean isNumber(String s)
    {
        s = s.trim();

        if (s.length() == 0) return false;

        StringIterator iter = new StringIterator(s);

        // check sign
        if (iter.skipNext("+-") && !iter.hasNext()) return false;

        // if only one char is available - it should be a digit
        if (iter.available() == 1) return isValidDigit(iter.next(), DigitBase.Dec);

        DigitBase digitBase = DigitBase.Dec; // decimal by default

        boolean hasIntegerPart = false;
        boolean hasFracPart = false;

        // check next numbers
        if (iter.skipNext("0"))
        {
            // simple zero
            if (!iter.hasNext()) return true;

            if (iter.skipNext("xX"))
            {
                if (!iter.hasNext()) return true;
                digitBase = DigitBase.Hex;
            }
            else
            {
                hasIntegerPart = true;
            }
        }

        boolean hasDecimalPoint = false;
        boolean hasExponent = false;

        // check chars one by one
        while (iter.hasNext())
        {
            char c = iter.next();

            if (c == ' ')
            {
                return false; // can't have any spaces
            }
            else if (c == '.')
            {
                // can only have a single decimal point and no exponent yet
                if (hasDecimalPoint || hasExponent || digitBase != DigitBase.Dec) return false;

                hasDecimalPoint = true;
            }
            else if (isValidDigit(c, digitBase)) // valid character for the selected base
            {
                if (hasDecimalPoint)
                {
                    hasFracPart = true; // if decimal point was found - then we have a fracture part
                }
                else if (!hasExponent)
                {
                    hasIntegerPart = true; // if exponent was not found - we have an integer part
                }
            }
            else if (oneOf(c, "eE")) // found exponent?
            {
                if (!iter.hasNext()) return false; // if no character after - invalid number

                // we should have a single exponent and at least either an integer or a fracture part
                if (hasExponent || !hasIntegerPart && !hasFracPart) return false;

                hasExponent = true;

                // an optional +/- sign
                if (iter.skipNext("-+") && !iter.hasNext()) return false;

                digitBase = DigitBase.Dec; // HACK: only expect decimal digits
            }
            else
            {
                return false; // something unexpected
            }
        }

        return true; // all good!
    }

    /** Is a valid digit for the selected base */
    private boolean isValidDigit(char c, DigitBase digitBase)
    {
        switch (digitBase)
        {
            case Hex: return c >= '0' && c <= '9' || c >= 'a' && c <= 'f' || c >= 'A' && c <= 'F';
        }
        return c >= '0' && c <= '9';
    }

    /** True is char is one of the characters from the string */
    private boolean oneOf(char c, String chars)
    {
        return chars.indexOf(c) != -1;
    }
}

- Alex Lementuev October 11, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

function isNumber(numStr) {
     var strArr = numStr.split('');
     var nonNumCharEncounterd = false;
     for (var i = 0; i < strArr.length; ++i) {
         var charCode = strArr[i].charCodeAt(0);
         if (charCode < 47 || charCode > 57) {
             nonNumCharEncounterd = true;
         }
     }
     return !nonNumCharEncounterd;
}

- Coa1z October 24, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
-1
of 1 vote

Looks for ASCII values from 48-57

- Himanshu Jain January 13, 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