HackerRank : Week of Code 32 – Duplication

By | May 15, 2017
Duplication : Hackerrank

Consider a binary string, s, with an initial value of “0” . We expand s by performing the following steps:

  1. Create a string, t, where each character ti  is equal to 1- si. For example, if s=”01″ , then t=”10″. Note that t and s always have the same length because t is the complement of s.
  2. Append t to the end of s so that s expanded = s initial + t s initial  . In the example above s , becomes “0110” .
  3. We keep on expanding s using steps 1 and 2  till the length of s is not above 1000 .

When we repeat the expansion operation, string grows like this:


Given q  queries in the form of a zero-based index, x, solve each query by printing the character at index x in s on a new line

Input Format
The first line contains an integer denoting q (number of queries).
Each of the q subsequent lines contains an integer describing the value of x  for a query.
Output Format
For each query, print the value of  s[x] (i.e., either 0 or 1 ) on a new line.

Sample Input 0

3
2
5
7

Sample Output 0

1
0
1

Solution

Pretty easy problem. You just have to work to create the string as mentioned.
Code:

package weekOfCode32;

import java.util.Scanner;

public class Duplication {

	public static StringBuilder compliemnt(StringBuilder sB) {
		StringBuilder st = new StringBuilder();
		for (int i = 0; i < sB.length(); i++) {
			char ch = sB.charAt(i);
			if (ch == '1')
				ch = '0';
			else
				ch = '1';
			st.append(ch);
		}
		return st;
	}

	public static void main(String[] args) {

		@SuppressWarnings("resource")
		Scanner scan = new Scanner(System.in);

		int n = scan.nextInt();
		StringBuilder s = new StringBuilder("0");

		StringBuilder st = new StringBuilder();

		while (st.length() <= 1000) {
			st = new StringBuilder();
			StringBuilder t = compliemnt(s);
			st.append(s).append(t);
			s = null;
			s = st;
		}
		for (int i = 0; i < n; i++) {
			int x = scan.nextInt();
			System.out.println(st.charAt(x));

		}

	}

}