DDSA Solutions

Last Digit of a^b

Time: O(len(b))
Space: O(1)

Problem Overview

The last digit of a^b depends only on the last digit of a and the exponent modulo 4 (for bases 2, 3, 7, 8).

Advertisement

Intuition

The last digit of a^b depends only on the last digit of a and the exponent modulo 4 (for bases 2, 3, 7, 8). a and b can be huge strings — never parse them fully. Special cases: b = "0" gives last digit 1; a = "0" gives 0. Reduce b using its last two digits mod 4; if the remainder is 0, use 4 instead so the power cycle is correct.

Algorithm

  1. 1If b equals "0", return 1.
  2. 2If a equals "0", return 0.
  3. 3Let num1 = last digit of a.
  4. 4Let num2 = last two digits of b (or last digit if shorter); set num2 = num2 % 4, then if num2 == 0 use 4.
  5. 5Return (num1^num2) % 10.

Example Walkthrough

Input: a = "12", b = "34"

  1. 1. Last digit of a → 2.
  2. 2. Last two digits of b → 34; 34 % 4 = 2.
  3. 3. 2^2 = 4 → last digit 4.
  4. 4. Check: 12^34 ends in 4.

Output: 4

Common Pitfalls

  • b = "0" means a^0 → last digit 1, not 0.
  • When b % 4 == 0, use exponent 4 — a^0 would break the 2/3/7/8 cycle.
  • Only the last one or two digits of b are needed for mod 4; do not use BigInteger for full b.
Last Digit of a^b.java
Java
// Approach: Last digit of a^b depends only on the last digit of a and b mod 4 (with 0 mapped to 4).
// Handle b = "0" → 1 and a = "0" → 0. Read the last two digits of b when long, then reduce exponent mod 4.
// Raise the base last digit to that small exponent and return mod 10.
// Time: O(len(b)) Space: O(1)
class Solution {

    public int getLastDigit(String a, String b) {
        if (b.equals("0")) {
            return 1;
        }
        if (a.equals("0")) {
            return 0;
        }

        int num1 = a.charAt(a.length() - 1) - '0';
        int num2 = b.charAt(b.length() - 1) - '0';

        if (b.length() >= 2) {
            int len = b.length();
            num2 = Integer.parseInt(b.substring(len - 2, len));
        }

        int mod = num2 % 4;
        num2 = mod == 0 ? 4 : mod;

        int res = (int) Math.pow(num1, num2);
        return res % 10;
    }
};
Advertisement
Was this solution helpful?