Java Program to Increment by 1 to all the Digits of a given Integer
Last Updated :
24 Nov, 2020
Given an integer, the task is to generate 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 will create a number which will be of the same length as the input and will contain only 1 in it. Then we will add them.
- Take the integer input.
- Find its length and then generate the number containing only 1 as digit of the length.
- Add both numbers.
- Print the result.
Java
import java.util.*;
import java.io.*;
class GFG {
public static void main(String[] args)
{
int number = 110102 ;
String string_num = Integer.toString(number);
int len = string_num.length();
String add = "" ;
for ( int i = 0 ; i < len; i++) {
add = add.concat( "1" );
}
int str_num = Integer.parseInt(add);
System.out.println(number + str_num);
}
}
|
Approach 2:
In this approach, we will take an integer variable with value 1, we will multiply that variable with 10 and keep on adding the variable to the number till both of them have the same length.
- Take the integer input.
- Add value 1 to the input.
- Multiply 1 with 10 and again add them.
- Keep on repeating step 2 and 3 till both of them have the same length.
- Print the result.
Java
import java.util.*;
import java.io.*;
class GFG {
public static void main(String[] args)
{
int number = 110102 ;
int add = 1 ;
for ( int i = 0 ; i < String.valueOf(number).length();
i++) {
number = number + add;
add = add * 10 ;
}
System.out.println(number);
}
}
|
Time Complexity: O(l) where l is the length of an integer.
Space Complexity: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...