TopCoder problem "BinaryIncrementation" used in SRM 338 (Division II Level One)



Problem Statement

    

The binary numeral system (base 2 numerals) represents numeric values using two symbols: 0 and 1. Counting in binary is similar to counting in any other number system. If you want to increase a number by 1, try to increase its last digit by 1. If this fails, set the last digit to zero, and try to increase the previous digit, and so on, until you succeed.

For example, the decimal sequence:

1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ...

converted to binary looks as follows:

1, 10, 11, 100, 101, 110, 111, 1000, 1001, 1010, 1011, ...

You are given a String x that contains the binary representation of a positive integer X. Write a method that will return a String containing the binary representation of (X+1). The returned String must not contain leading zeroes.

 

Definition

    
Class:BinaryIncrementation
Method:plusOne
Parameters:String
Returns:String
Method signature:String plusOne(String x)
(be sure your method is public)
    
 

Constraints

-x will contain between 1 and 30 characters, inclusive.
-Each character in x will be a one ('1') or a zero ('0').
-The first character in x will be a one ('1').
 

Examples

0)
    
"10011"
Returns: "10100"
"10011" is binary for 16+2+1 = 19. The next integer is 20 = 16+4, which is "10100" in binary.
1)
    
"10000"
Returns: "10001"
2)
    
"1111"
Returns: "10000"
Be careful not to miss the case when the result is a power of two.
3)
    
"1"
Returns: "10"
4)
    
"101010101010101010101010101010"
Returns: "101010101010101010101010101011"

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=7385

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10662&pm=7385

Writer:

misof

Testers:

PabloGilberto , brett1479 , Olexiy , ged

Problem categories:

Simple Math, String Manipulation