'Facing Runtime error while submission in Hacker Earth Problem: Cyclic shifts

Problem statement in HackerEarth:

A large binary number is represented by a string A of size N and comprises of 0s and 1s. You must perform a cyclic shift on this string. The cyclic shift operation is defined as follows:

If the string A is [A0,A1,A2,...,AN−1], then after performing one cyclic shift, the string becomes [A1,A2,...,AN−1,A0]. You performed the shift infinite number of times and each time you recorded the value of the binary number represented by the string. The maximum binary number formed after performing (possibly 0) the operation is B. Your task is to determine the number of cyclic shifts that can be performed such that the value represented by the string A will be equal to B for the Kth time.

Yet all the sample cases for cleared, I faced Runtime error while submitting. Can someone tell me where I went wrong? code:

import java.util.*;
class TestClass {
    public static void main(String args[] ) throws Exception {
        Scanner s = new Scanner(System.in);
        long N = s.nextInt();
        for(int o=0;o<N;o++) //to loop through test cases
        {
        long n1 = s.nextInt();
        long k = s.nextInt();
        String S = s.next();
        int max = 0;
        int d,n=0,j,p=-1; // p for periodicity in the given inout which influence on max('B') //repetation
        char str;
       for(int i=0;i<n1;i++)   //To find max and also periodicity 
       {
           StringBuffer b = new StringBuffer(S);
            d = Integer.parseInt(S,2);
            if(max<d)
            {
            max = d;
            n=i;
            }
            else if(max == d)
            {
                p=i-n;
                break;
            }
            str = S.charAt(0);    //to left shift with constant complexity
            b.deleteCharAt(0);
            S = b.toString()+Character.toString(str);
       }   
       if(p==-1)
       {
           System.out.println((n+(k-1)*n1)%(10^9+7));
       }
       else
       System.out.println((n+(k-1)*p)%(10^9+7));
        }
    }
}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source