Linkedin Interview Question
Software Engineer / DevelopersCountry: United States
Interview Type: Phone Interview
/*
* Returns true if the input string is a number and false otherwise
*/
/*
* Examples:
* isNumber(12) -> true
* isNumber("one") -> false
* isNumber(23.2) -> true
* isNumber(0) -> true
* isNumber(-23) -> true
*/
public static boolean isNumber(String toTest)
{
boolean flag = false;
// implementation here
String pattern = "(-?\\d+)|(-?\\d+\\.\\d+)";
flag = toTest.matches(pattern);
return flag;
}
I like this solution. However if we are going to use Java's fancy functions why not just do this:
public static boolean isNumber(String toTest)
{
try
{
Double.parseDouble(toTest); //Throws exception if not a valid number
return true;
}
catch(Exception e)
{
return false;
}
}
public static long parseInt (String s) throws NumberFormatException {
boolean neg = false;
if(s.startsWith("-")){
neg = true;
s = s.substring(1);
}
int len = s.length();
long result = 0;
for(int i=0;i<len;i++) {
if(s.charAt(i) < 48 || s.charAt(i) > 57)
throw new NumberFormatException("Invalid Number");
int test = (s.charAt(i) - '0');
result = result * 10;
result = result + test;
}
if(neg){
return -result;
}
return result;
}
--Use the above function and catch NumberFormatException to determine isNumber.
I personally like the regex solution but wonder if that's what the interviewers are looking for...so i just implement a function to check if a string is a number.
public static boolean isDigit(char c){
if(c>='0' && c<='9'){
return true;
}else{
return false;
}
}
public static boolean isNumber(String s){
if(s.length() == 0){
return false;
}
boolean dotUsed = false;
for(int i=0;i<s.length();i++){
if(i==0){
//first digit can only be -, ., or 0-9
if(s.charAt(i) == '-'){
continue;
}
if(s.charAt(i) == '.'){
dotUsed = true;
continue;
}
if(!isDigit(s.charAt(i))){
return false;
}
}else{
//only one dot allowed
if(s.charAt(i) == '.'){
if(dotUsed){
return false;
}else{
//dont allow "10."
if(i==s.length()-1){
return false;
}else{
dotUsed = true;
continue;
}
}
}
//dont allow cases like 0000002
if(i==1 && s.charAt(0) == '0' && s.charAt(1)=='0'){
return false;
}
if(!isDigit(s.charAt(i))){
return false;
}
}
}
return true;
}
The rules to be implemented depends on what is defined as a number. The following program accepts one + or - as prefix, one .(dot) at anywhere except the end, arbitrary number of 0s as prefix.
public class IsNumber {
//valid numbers: -1, -1.2, +1, +0.1, +1.0
//invalid numbers: --1, -+1. -1.2.3
public static boolean isN(String str) {
boolean hasSign = false;
boolean hasDot = false;
if (str==null || str.length()<1) return false;
char c = str.charAt(0);
if (c=='-'||c=='+') hasSign = true;
else if (c=='.') hasDot = true;
else if (c>'9' || c<'0') return false;
for (int i=1; i<str.length(); i++) {
c = str.charAt(i);
if (hasSign && (c=='+' || c=='-')) return false;
else if (c=='.') {
if (hasDot) return false;
else hasDot = true;
}
else if (c>'9' || c<'0') return false;
}
return str.charAt(str.length()-1)!='.'; //exclude last char be dot.
}
public static void main(String[] args) {
String[] testStr = new String[] {"-1", "-1.2", "+1", "+1.0", ".3", "1.3", "c.3", "--1", "-+1", "1.2.3", "-1.2.3", "3.", "12c" };
for(String s:testStr) {
System.out.printf("%b, ", isN(s));
}
}
}
public class TestNumeric {
private boolean isNumeric(String input) {
// TODO Auto-generated method stub
try {
double number = Double.parseDouble(input);
} catch (NumberFormatException exception) {
return false;
}
return true;
}
public boolean isNumber(String toTest) {
toTest = toTest.trim();
// implement this
if (toTest == null)
return false;
else {
int i = 0;
if (toTest.charAt(i) == '-') {
i++;
}
int floatPointCounter = 0;
while (i < toTest.length()) {
if (toTest.charAt(i) == '.' && floatPointCounter < 1) {
floatPointCounter++;
} else if (toTest.charAt(i) > '9' || toTest.charAt(i) < '0'
|| floatPointCounter > 1) {
return false;
}
i++;
}
return true;
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
String input = " -5";
TestNumeric tN = new TestNumeric();
System.out.println("Numeric Status: " + tN.isNumeric(input));
System.out.println("Numeric Status: " + tN.isNumber(input));
}
}
Please go through the string each char by char
- Hari April 03, 2014compare with ASCII value if it is between 48 to 57.
Then it is a num.