Given a non-empty array of decimal digits representing a non-negative integer, increment one to the integer.
The digits are stored such that the most significant digit is at the head of the list, and each element in the array contains a single digit.
You may assume the integer does not contain any leading zero, except the number 0 itself.
Example 1:
Input: arr= [5,3,2]
Output: [5,3,3]
Example 2:
Input: arr= [9,9]
Output: [1,0,0]
Approach
Java
import java.util.Arrays;public class PlusOne {public static void main(String[] args) {int arr[] = { 9, 9 };int plusOne[] = plusOne(arr);System.out.println("Plus one " + Arrays.toString(plusOne));}// Method for plus one in arraypublic static int[] plusOne(int[] digits) {// create result arrayint[] result = new int[digits.length + 1];int carry = 0;// Iterate till 0for (int i = digits.length - 1; i >= 0; i--) {int k = 0;if (i == digits.length - 1) {k = digits[i] + 1 + carry;} else {k = digits[i] + carry;}carry = 0;if (k > 9) {carry = k / 10;k = k % 10;}result[i] = k;}if (carry > 0)result[0] = carry;elseresult = Arrays.copyOf(result, digits.length);return result;}}
C++
#include <bits/stdc++.h>using namespace std;//function to add 1 into//the number formed by listvector<int> plusOne(vector<int>& digits){//lenght of numberint n=digits.size();//varible to hold the carryint carry=0;//vector array to hold the//final resultvector<int> res;//iterate for all the digits//from endfor(int i=n-1;i>=0;i--){//if at last digitif(i==n-1){//push into the result after adding//1 and convert into single digitres.push_back((carry+digits[i]+1)%10);//get carry for next iterationcarry=(carry+digits[i]+1)/10;}//not at last digitelse{//simply add the current digit with//the carry and convert into//single digitres.push_back((carry+digits[i])%10);//take carry for next roundcarry=(carry+digits[i])/10;}}//if after all iteration//if carry then push into//the final reusltif(carry)res.push_back(carry);//revers the final resultreverse(res.begin(),res.end());//return the final resultreturn res;}int main(){vector<int> digits={9,9};vector<int> plusone=plusOne(digits);for(int i=0;i<plusone.size();i++)cout<<plusone[i]<<" ";return 0;}
No comments:
Post a Comment