66. 加一问题 Plus One

Given a non-negative integer represented as a non-empty array of digits, plus one to the integer.

You may assume the integer do not contain any leading zero, except the number 0 itself.

The digits are stored such that the most significant digit is at the head of the list.

题意:给出一个非负的数,用数组来表示这个数,比如说9999就是[9,9,9,9]当对这个数加一的时候,将这个数用数组的形式返回。

  1. public class Solution {
  2. public int[] PlusOne(int[] digits) {
  3. int plus = 1;
  4. List<int> resultList = new List<int>();
  5. for (int i = digits.Length - 1; i >= 0; i--) {
  6. if (plus > 0) {
  7. digits[i] += 1;
  8. if (digits[i] >= 10) {
  9. digits[i] = digits[i] % 10;
  10. } else {
  11. plus--;
  12. }
  13. }
  14. resultList.Add(digits[i]);
  15. if (i == 0 && plus == 1) {
  16. resultList.Add(1);
  17. }
  18. }
  19. resultList.Reverse();
  20. return resultList.ToArray();
  21. }
  22. }





原文地址:https://www.cnblogs.com/xiejunzhao/p/d33f14cb837d4f624b1e6004cc99ec6a.html