Linkedin Interview Question
Developer Program EngineersCountry: United States
Interview Type: Phone Interview
//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;
}
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;
}
}
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
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;
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;
}
}
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
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());
}
}
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
}
}
}
}
/**
* 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;
}
}
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');
}
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');
}
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;
}
/**
*
* 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);
}
}
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;
}
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");
}
}
}
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;
}
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;
}
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;
}
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;
}
- naren November 11, 2014