Your method will only work if b equals 2, which is same as exponentiation by squaring but it will fail in cases with b > 2. Here's how:
Your string n can contain numbers in the range [0,b-1] as it is the representation of number n in base b. In your code, you only check for digit 1, and in the case of b = 7, there can be any digit in the range [0,6]. You have to modify your algorithm as follows :
// take appropriate remainders where required
// Correction 1 :
In the for loop,
Check if a[i] = 1, then x = x * power
else if a[i] = 2, then x = x * power^2
else if a[i] = 3, then x = x * power^3
.
.
.
.
till a[i] = b-1, then x = x * power^(b-1)
// Correction 2 :
After checking a[i]
power = power^b and not power = power^2 which is only good for b = 2
You should now get the correct answer.