LinkedIn Interview Question

Write a function to determine if a string is an integer.

Interview Answers

Anonymous

Feb 24, 2013

#include #include int main(){ string str = ""; int len = str.length(); for (int i=0;i57){ return 0; } } return 1; }

3

Anonymous

Mar 1, 2013

Actually my previous answer is incomplete. I don't check for negative numbers, nor decimal points. #include #include bool checknumber(string str){ int len = strlen(str); if ( (len==0) || (!str) ) return false; if (str[len-1] == '.') return false; bool flag = false; for (int i=0; i57){ return false; } if (str[i] =='.'){ if (flag){ return false; } flag = true } } } return 1; }

Anonymous

Mar 1, 2013

Andddd I forgot negative number check. That's just a simple if(str[0] == '-') check.

Anonymous

Feb 19, 2015

def is_digit(thing): if not isinstance(thing, basestring): return ValueError('Argument needs to be of instance basestring.') # Be nice and strip whitespace. thing = thing.strip() # If there is nothing there, bail. if thing == '': return False # If there is more than 1 decimal, bail. if thing.count('.') > 1: return False # Sort of a special case. If the number is a negative, just strip it out. if thing.startswith('-'): # Do another strip. We are explicitly allowing for space after the negative. thing = thing[1:].lstrip() # If there are characters left over after all valid characters were stripped, # then something is invalid. if re.sub(VALID_RE, '', thing) != '': return False return True

Anonymous

Jan 14, 2013

Java version: boolean checkInt(String s){ try{ Integer.parseInt(s) } catch(NumberFormatException e){ return False;} return True; } Java version without try/catch: public static boolean isInt(String s){ for (int i=0; i

2

Anonymous

Aug 13, 2014

public boolean isInteger(String s) { if(s.indexOf('.') == -1) return false; if(s.indexOf('-') > 0) return false; return true; }