We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
publicstaticStringencryption(Strings){// Write your code here/* * Understanding test cases: - If length is k^2, then: k <= row <= col <= k -> a square (k rows). - If length is k^2 - 1, then: k-1 <= row <= col <= k -> k rows - If length is k^2 + 1, then: k <= row <= col <= k+1 -> k x (k+1) - If length is k^k + k + 1, then: row x col = (k + 1)^2 * Step: - Remove space, get the modified one. - Calculate the length, the row and col. - Using loop to change the format. - Return the result. * Idea to change format: - Connect the word in index k with word in index (k+row). - Using an outer loop to monitor formatted words. - Using an inner loop to monitor character in a word. - Have a condition to check if the next index is in the string. *///InitStringstring=s.replaceAll("\\s","");intlength=s.length();introw=(int)Math.sqrt(length);intcol;//Row and columnif(row*row==length){col=row;}elseif(row*(row+1)>=length)col=row+1;else{row++;col=row;}//FormatStringBuildersb=newStringBuilder();for(inti=0;i<col;i++){for(intj=0;j<row;j++){if(i+j*col<length){sb.append(string.charAt(i+j*col));}elsebreak;}sb.append(" ");}returnsb.toString();}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Encryption
You are viewing a single comment's thread. Return to all comments →
My solution in Java language: