lossy conversion from double to int for Rabin Karp Algorithm Code

34 Views Asked by At

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

There are 1 best solutions below

5
On

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