leetcode--Plus One

来源:互联网 发布:煤炭行业数据 编辑:程序博客网 时间:2024/05/21 08:53

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.


题意:给定一个数组,元素都是非负数,整个数组用于表示一个整数。现在这个整数加1,求加1后的数组。

分类:数组,数学


解法1:从后往前加,注意保留flag来表示进位。

[java] view plain copy
  1. public class Solution {  
  2.     public int[] plusOne(int[] digits) {  
  3.         int len = digits.length;  
  4.         int[] res = new int[len+1];  
  5.         int flag = 1;  
  6.         for(int i=len-1;i>=0;i--){  
  7.             int t = digits[i]+flag;  
  8.             flag = t/10;  
  9.             digits[i] = t%10;  
  10.             res[i] = t%10;  
  11.         }  
  12.         if(flag==1){  
  13.             res[0] = 1;  
  14.             return res;  
  15.         }  
  16.         return digits;  
  17.     }  

原文链接http://blog.csdn.net/crazy__chen/article/details/46008945

原创粉丝点击