LeetCode: Plus One

考vector的insert操作,一次过

 1 class Solution {

 2 public:

 3     vector<int> plusOne(vector<int> &digits) {

 4         // Start typing your C/C++ solution below

 5         // DO NOT write int main() function

 6         int carry = 0;

 7         digits[digits.size()-1]++;

 8         for (int i = digits.size()-1; i >= 0; i--) {

 9             digits[i] += carry;

10             carry = digits[i]/10;

11             digits[i] %= 10;

12         }

13         if (carry) digits.insert(digits.begin(), carry);

14         return digits;

15     }

16 };

 C#

 1 public class Solution {

 2     public int[] PlusOne(int[] digits) {

 3         int c = 0;

 4         digits[digits.Length-1]++;

 5         for (int i = digits.Length-1; i >= 0; i--) {

 6             digits[i] += c;

 7             c = digits[i] / 10;

 8             digits[i] %= 10;

 9         }

10         if (c > 0) {

11             int[] ans = new int[digits.Length+1];

12             ans[0] = c;

13             for (int i = 1; i <= digits.Length; i++) ans[i] = digits[i-1];

14             return ans;

15         }

16         else {

17             int[] ans = new int[digits.Length];

18             digits.CopyTo(ans, 0);

19             return ans;

20         }

21     }

22 }
View Code

 

你可能感兴趣的:(LeetCode)