66 Plus One, 66 plusone
Given a non-negative number represented as an array of digits, plus one to the number.
The digits are stored such that the most significant digit is at the head of the list.
The question indicates that a non-negative number is given in this way and an array is used to represent this number. For example, 9999 is [9, 9, 9] When we add one to this number, return this number in the form of an array.
It is easy to think of a simple method, set a carry, first judge whether to generate a carry (equal to 10) after adding 1 to the last element of the array. If generate a carry, set this element to 0, other elements are the same operation. Here is a tip. The question is about the number + 1, so we can think that the starting carry is 1. When one element is less than 10, the array is directly returned. When the highest bit is not returned after execution, that is, the highest bit generates a carry, a new array is generated, and the highest bit is 1, the remaining values are 0.
1 public class Solution {2 public int [] plusOne (int [] digits) {3 int n = digits. length; 4 int jinwei = 1; 5 int I; 6 for (I = n-1; I> = 0; I --) {7 digits [I] + = jinwei; 8 if (digits [I] <10) 9 return digits; 10/* with a forward position */11 else12 digits [I] = 0; 13} 14/* indicates that the highest bit has a forward digit */15 int [] newdigits = new int [n + 1]; 16 newdigits [0] = 1; 17 for (int k = 1; k <n + 1; k ++) 18 newdigits [k] = 0; 19 return newdigits; 20} 21}
The following is the online C ++ code.
1 class Solution {2 public: 3 vector <int> plusOne (vector <int> & digits) {4 5 int size = digits. size (); 6 7 if (digits [size-1] <9) 8 {9 digits [size-1] + = 1; 10 return digits; 11} 12 13 // do you need to carry 14 bool carry = true; 15 16 for (int I = size-1; I> = 0; I --) 17 {18 if (! Carry) 19 {20 break; 21} 22 23 if (digits [I] = 9) 24 {25 carry = true; 26 27 // After carry, original position 028 digits [I] = 0; 29 30 if (I = 0) 31 {32 // after the first digit of the array is carried, You need to insert the first digit 33 digits. insert (digits. begin (), 1); 34} 35} 36 else37 {38 // if not carried, 39 carry = false is exited; 40 digits [I] + = 1; 41} 42} 43 44 return digits; 45} 46 };
Another question ~~ 233333