Naruto
Naruto

Reputation: 9634

Check number string start with 00 or 0

is there a optimized way to identify a number string start with Single zero, double or triple zero.

For eg: 01234 -- Single zero
001234 -- double
00023232 -- triple.

I know that, one way is traversing one by one based on the position and check its zero or not. But apart from this, is there a better way?

Thanks

Upvotes: 0

Views: 3976

Answers (2)

weston
weston

Reputation: 54781

I know that, one way is traversing one by one based on the position and check its zero or not. But apart from this, is there a better [more optimal] way?

No, looping would be the easiest and fastest way I would think to count leading zeros.

This code counts up to max of three as that seems to be what you want:

public static int leadingZerosCount(String s){
   int zeros=0;
   for(int i=0;i<3 && i<s.length();i++) {
      if(s.charAt(i)=='0')
        zeros++;
      else
        break;
   }
   return zeros;
}

Regex version and tests

import java.util.regex.Matcher;
import java.util.regex.Pattern;

private final Pattern pattern = Pattern.compile("[0]{0,3}");

public int leadingZeros(String numberString) {
    Matcher matcher = pattern.matcher(numberString);
    matcher.find();
    return matcher.group().length();
}

@Test
public void empty(){        
    assertEquals(0, leadingZeros(""));
}

@Test
public void none(){     
    assertEquals(0, leadingZeros("1"));
}

@Test
public void one(){      
    assertEquals(1, leadingZeros("01"));
}

@Test
public void two(){      
    assertEquals(2, leadingZeros("001"));
}

@Test
public void three(){        
    assertEquals(3, leadingZeros("0001"));
}   

@Test
public void more_than_three(){      
    assertEquals(3, leadingZeros("00001"));
}

@Test
public void two_but_not_leading(){      
    assertEquals(0, leadingZeros("1001"));
}

Upvotes: 3

Nicolas Buquet
Nicolas Buquet

Reputation: 3955

You can simply use the 'startsWith' method of the String class:

boolean startWithZeros(String str, integer countOfZeroes) {
    StringBuilder sb = new StringBuilder();
    for( integer i = 0; i < coutOfZeroes; i++ )
    sb.append("0");
    return str.startsWith(sb.toString());
}

Upvotes: 2

Related Questions