Sure, here's a Python function to add one to a number represented as an array of digits:
def add_one(digits):
n = len(digits)
# Traverse the array from right to left
for i in range(n - 1, -1, -1):
# If the current digit is less than 9, simply increment it by 1 and return
if digits[i] < 9:
digits[i] += 1
return digits
else:
# If the current digit is 9, set it to 0 and continue to the previous digit
digits[i] = 0
# If we reached here, it means all digits were 9, so we need to add a new digit 1 at the beginning
digits.insert(0, 1)
return digits
# Example usage
digits = [1, 2, 9]
print("Original Number:", digits)
print("Number after adding one:", add_one(digits))