Given an integer, the task is to get a Java Program to Increment by 1 All the Digits of a given Integer.
Examples:
Input: 12345 Output: 23456 Input: 110102 Output: 221213
Approach 1: In this approach, we create a number that is the same length as the input and contains only 1. Then we will add it up.
// Java Program to Increment by 1 All the Digits of a given // Integer // Importing Libraries import java.util.*; import java.io.*; class GFG { // Main function public static void main(String[] args) { // Declaring the number int number = 110102; // Converting the number to String String string_num = Integer.toString(number); // Finding the length of the number int len = string_num.length(); // Declaring the empty string String add = ""; // Generating the addition string for (int i = 0; i < len; i++) { add = add.concat("1"); } // COnverting it to Integer int str_num = Integer.parseInt(add); // Adding them and displaying the result System.out.println(number + str_num); } }
Output
221213
Approach 2:
// Java Program to Increment by 1 All the Digits of a given // Integer // Importing Libraries import java.util.*; import java.io.*; class GFG { // Main function public static void main(String[] args) { // Declaring the number int number = 110102; // Declaring another variable with value 1 int add = 1; for (int i = 0; i < String.valueOf(number).length(); i++) { // Adding variable add and number number = number + add; // Multiplying value of the add with 10 add = add * 10; } // Printing result System.out.println(number); } }
Output
221213
Time Complexity: O(l) where l is the length of an integer.
Space Complexity: O(1)
Australia
UK
UAE
Singapore
Canada
New
Zealand
Malaysia
USA
India
South
Africa
Ireland
Saudi
Arab
Qatar
Kuwait
Hongkong
Copyright 2016-2023 www.programmingshark.com - All Rights Reserved.
Disclaimer : Any type of help and guidance service given by us is just for reference purpose. We never ask any of our clients to submit our solution guide as it is, anywhere.