Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Not getting the result what I want in java by using array and string?

Input:-

agxgw
3
2 4
2 5
7 14

Output:-

Yes
No
Yes

I just answer with “Yes” or “No” using the following rule: I will just select two integers a and b, if the element at the position a is same as the element as position b in the non-ending chant. Answer Yes, otherwise say No.

Code:

import java.util.Scanner;

public class Gf {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner sc = new Scanner(System.in);        
        String k=sc.next();
        int k1=k.length();
        int a=sc.nextInt();
        for (int i =0; i <a; i++) {
            int b=sc.nextInt();
            int b1=b%k1;
            int c=sc.nextInt();
            int c1=c%k1;
            if(k.charAt(b1)==k.charAt(c1)) {
                System.out.println("yes");
            } else {
                System.out.println("No");
            }
        }
    }
}
like image 405
ansh Avatar asked Mar 19 '26 11:03

ansh


1 Answers

String#charAt is zero-index based, and the values in b1 and c1 assume it's one-index based.

Solution: decrease b1 and c1 before evaluating k#charAt. Do this only if their values are greater than zero.

int b=sc.nextInt();
int b1=b%k1;
int c=sc.nextInt();
int c1=c%k1;
b1 = b1 == 0 ? k1 - 1 : b1 - 1;
c1 = c1 == 0 ? k1 - 1 : c1 - 1;
like image 185
Luiggi Mendoza Avatar answered Mar 22 '26 02:03

Luiggi Mendoza