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.
/*
* Complete the 'encryption' function below.
*
* The function is expected to return a STRING.
* The function accepts STRING s as parameter.
*/
public static String encryption(String s) {
// Remove spaces
s = s.replaceAll("\\s", "");
int len = s.length();
// Calculate rows and columns
int rows = (int) Math.floor(Math.sqrt(len));
int cols = (int) Math.ceil(Math.sqrt(len));
if (rows * cols < len) {
rows++;
}
// Build the encrypted string
StringBuilder encrypted = new StringBuilder();
for (int c = 0; c < cols; c++) {
for (int r = 0; r < rows; r++) {
int index = r * cols + c;
if (index < len) {
encrypted.append(s.charAt(index));
}
}
encrypted.append(" ");
}
return encrypted.toString().trim();
}
}
public class Solution {
public static void main(String[] args) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));
String s = bufferedReader.readLine();
String result = Result.encryption(s);
bufferedWriter.write(result);
bufferedWriter.newLine();
bufferedReader.close();
bufferedWriter.close();
}
}
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 →
import java.io.; import java.util.; import java.util.stream.*;
class Result {
}
public class Solution { public static void main(String[] args) throws IOException { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));
}