Given a decimal number m. Convert it into a binary string and apply n iterations, in each iteration 0 becomes 01, and 1 becomes 10. Find the kth (1-indexing) character in the string after nth iteration.
Example 1:
Input: m = 5, n = 2, k = 5 output: 0 Explanation: Binary represntation of m is "101", after one iteration binary reprentation will be "100110", and after second iteration binary repreentation will be "100101101001".
Here is my code:
class Solution
{
char kthCharacter(int m, int n, int k)
{
String s1=Integer.toBinaryString(m);
String str1="";
for(int j=0;j<n;j++)
{
str1="";
for(int i=0;i<s1.length();i++)
{
if(s1.charAt(i)=='0' && s1.charAt(i)!='1')
{
str1=str1+"01";
}
else
{
str1=str1+"10";
}
}
s1=str1;
}
// System.out.println(str1);
return str1.charAt(k-1);
}
}
When I compile I get the output, upon submission of code, I get the error as ava.lang.StringIndexOutOfBoundsException. Please help to check this.