Use app×
Join Bloom Tuition
One on One Online Tuition
JEE MAIN 2025 Foundation Course
NEET 2025 Foundation Course
CLASS 12 FOUNDATION COURSE
CLASS 10 FOUNDATION COURSE
CLASS 9 FOUNDATION COURSE
CLASS 8 FOUNDATION COURSE
0 votes
29 views
in Information Technology by (119k points)
Could you provide an example code to demonstrate add one to a number represented as an array of digits?

Please log in or register to answer this question.

1 Answer

0 votes
by (119k points)

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))

Welcome to Sarthaks eConnect: A unique platform where students can interact with teachers/experts/students to get solutions to their queries. Students (upto class 10+2) preparing for All Government Exams, CBSE Board Exam, ICSE Board Exam, State Board Exam, JEE (Mains+Advance) and NEET can ask questions from any subject and get quick answers by subject teachers/ experts/mentors/students.

Categories

...