Java: Plus one to the number of a specified positive numbers represented as an array of digits
Java Basic: Exercise-179 with Solution
Add One to Array Number
Write a Java program to add one to a positive number represented as an array of digits.
Sample array: [9, 9, 9, 9] which represents 9999
Output: [1, 0, 0, 0, 0].
Sample Solution:
Java Code:
// Importing necessary Java utilities
import java.util.*;
// Main class Solution
public class Solution {
// Main method
public static void main(String[] args) {
// Initializing an array of integers
int[] nums = {9, 9, 9, 9};
// Printing the original array
System.out.println("Original array: " + Arrays.toString(nums));
// Printing the array of digits after adding one to the input array
System.out.println("Array of digits: " + Arrays.toString(plus_One_digit(nums)));
}
// Method to add one to the last digit of the input array
public static int[] plus_One_digit(int[] digits_nums) {
// Looping through the array from the end to the start
for (int i = digits_nums.length - 1; i > -1; --i) {
// Checking if the digit is not 9
if (digits_nums[i] != 9) {
digits_nums[i] += 1; // Incrementing the digit by 1
// Setting the digits after the incremented digit to 0
for (int j = i + 1; j < digits_nums.length; ++j) {
digits_nums[j] = 0;
}
return digits_nums; // Returning the updated array
}
}
// If all digits are 9, creating a new array with an additional digit for carrying over 1
int[] result = new int[digits_nums.length + 1];
result[0] = 1; // Setting the first digit to 1
return result; // Returning the new array with the carried over 1
}
}
Sample Output:
Original array: [9, 9, 9, 9] Array of digits: [1, 0, 0, 0, 0]
Flowchart:
Java Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a Java program to get a new binary tree with same structure and same value of a given binary tree.
Next: Write a Java program to swap every two adjacent nodes of a given linked list.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/java-exercises/basic/java-basic-exercise-179.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics