Contents

qr code(with.Java)

   Sep 16, 2023     1 min read

This is a post about qr code (with.Java).

We’ll be solving a coding test problem, doing a retrospective on the problem we solved, and learning about other ways to solve it.

Let’s start with the problem.

Problem

Given two integers q, r and a string code, write a solution function that returns a string concatenating the characters at each index in code divided by q with the remainder being r, in order from front to back.

Example input and output
qrcoderesult
31“qjnwezgrpirldywt”“jerry”
10“programmers”“programmers”

My solution to the problem

class Solution {
    public String solution(int q, int r, String code) {
        StringBuilder sb = new StringBuilder();
        for(int i = 0; i < code.length(); i++){
            if(i % q == r) sb.append(code.charAt(i));
        }
        } return sb.toString();
    }
}
Solution

StringBuilder sb = new StringBuilder();: Create a StringBuilder object sb to build a new string.

for(int i = 0; i < code.length(); i++) {: Iterate over the string code, checking each character.

if(i % q == r) sb.append(code.charAt(i));: If the remainder of the current index i divided by q equals r, add the character at the current index to sb.

return sb.toString();: Finally, convert the characters stored in sb to a string and return them.

This code creates a new string by selecting the characters in the input string code where the remainder of q divided by r is in the same position as r. For example, if q is 3 and r is 1, it generates a new string by selecting characters whose indices in the string are multiples of 3: 1, 4, 7, 10, … etc.