-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
OnePlustoWhole.java
73 lines (61 loc) · 1.87 KB
/
OnePlustoWhole.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
/*
One plus to whole
For a given array arr[] of decimal digits, all of which are non-negative numbers.
The digits are stored such that the most significant is at the head of the list,
and each element of the array contaians single digit only.
It is assumed that none of the numbers have its most significant digit equal to 0.
Your task is to increment the interger so formed by one and return it.
*/
import java.util.*;
public class OnePlustoWhole
{
//function to return the incremented integer
public int[] onePlus(int arr[], int size)
{
for(int i=size-1; i>=0; i--)
{
//if element of the array are somethig less than 9 no carray
if(arr[i]<9)
{
arr[i]++;
return arr;
}
//else if array element is 9 then we crearw new array
//with one extra digit to keep carry
arr[i]=0;
}
int[] num=new int[size+1];
num[0]=1;
return num;
}
//DRIVER METHOD
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
//size of array
System.out.println("Enter the number of elements of array: ");
int size = sc.nextInt();
int []arr = new int[size];
//array elements
System.out.println("Enter the elements for array: ");
for (int i = 0; i < size; i++) {
arr[i] = sc.nextInt();
}
System.out.println("The incremented number is: ");
int[] res=new OnePlustoWhole().onePlus(arr, size);
for(int i=0; i<res.length; i++)
{
System.out.print(res[i]+" ");
}
}
}
/*
EXAMPLE:-
Input--
Enter the number of elements of array: 5
Enter the elements for array: [1, 2, 2, 5, 6]
Output--
The incremented number is: [1, 2, 2, 5, 7]
TIME COMPLEXCITY --> O(N)
SPACE COMPLEXITY --> O(N)
*/