Yours cannot possibly be right because
(int)Math.pow(10, (S.length() - i - 1))
for any string longer than 11 characters results in Integer.MAX_VALUE, for the first length-11 or length-12 characters. For example, for a 20-character string, when i == 0
in your loop, this is expression is
(int)Math.pow(10, (20-0-1))
1019 does not fit in an int
, so the result of the cast is 2147483647