-1

I was referring the code for Rabin karp algorithm. But inside the while loop it is Giving an error

possible lossy conversion from double to int. Can anyone please help me to resolve this error.

import java.util.Scanner;

public class Main {
    static boolean rabinKarp(String text, String pattern) {
        int pLength= pattern.length();
        int n=pLength-1;
        int res=0, curr=0;
        int i=0;
        for(;i<pLength;i++)
            res+= (pattern.charAt(i)-'a'+1)*Math.pow(10,n--);
        
        n=pLength-1;  
        for(i=0;i<pLength;i++)
            curr+= (text.charAt(i)-'a'+1)*Math.pow(10,n--);
        if(res==curr)
            return true;
        n=pLength-1;
        while(i<text.length()){
            int p= Math.pow(10,n);
            int sub= (text.charAt(i-pLength)-'a'+1)*p;
            int add= (text.charAt(i)-'a'+1);
            curr= (curr-sub)*10+add;
            if(res==curr)
                return true;
            i++;
        }
        return false;    
        
    }
    
   public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    String text = "abcbab";
    String pattern = "bab";
    System.out.println(rabinKarp(text,pattern));
  }

}

1 Answers1

0

the pow method from Math will give you a double, you have to cast it manually: int p= (int) Math.pow(10,n); see also Calculating powers of integers

Pavel
  • 785
  • 5
  • 14
  • I agree with you. But, if you see for loop written there also pow calculated data is stored in int there issue is not generated. can you tell me why? ``` for(;i – Coding Enthusiast Jan 05 '23 at 09:07
  • that is because the expression `(text.charAt(i) - 'a' + 1)` will be an `int` and then you would multiply int times double so the double will be casted to int – Pavel Jan 05 '23 at 09:12
  • Thanks for Reply, But the Question is still as it is because As you said `res+= (pattern.charAt(i)-'a'+1)*Math.pow(10,n--);` first integer * double will be integer inside the while loop where error is present `int sub= (text.charAt(i-pLength)-'a'+1)*p;` (text.charAt(i-pLength)-'a'+1) -> integer p is double and the multiplication is expected to perform and result should be int as you said but I got the error – Coding Enthusiast Jan 05 '23 at 09:19
  • you should get error on this line `int p= Math.pow(10,n);`, don't you? – Pavel Jan 05 '23 at 09:22
  • I got the error on line you mentioned. But same thing is written `res+=(pattern.charAt(i) - 'a'+1)*Math.pow(10,n--);` and `curr+= (text.charAt(i)-'a'+1)*Math.pow(10,n--);` Why error are not coming here. – Coding Enthusiast Jan 06 '23 at 06:58