前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LeetCode-66-Plus One

LeetCode-66-Plus One

作者头像
欠扁的小篮子
发布2018-04-11 11:23:58
5830
发布2018-04-11 11:23:58
举报
文章被收录于专栏:技术碎碎念

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.

题意:给定一个由数组表示的数字,加上一,返回由数组表示的结果

思路:

  参考Discuss的解法,对于每一位来说,只有等于9的时候才会进位,小于就的时候,数值加一然后返回本数组即可。

  如果最后数值进位后恰好比原值多一位,则直接new一个数组,默认值为0,赋值最高位为1,返回即可。

Java代码如下:

代码语言:javascript
复制
 1 public class Solution {
 2     public int[] plusOne(int[] digits) {
 3         if (digits.length==0)
 4             return digits;
 5         
 6         for (int i = digits.length -1; i>=0;i--) {
 7             if (digits[i] < 9) {
 8                 digits[i]++;
 9                 return digits;
10             }
11             digits[i] = 0;
12         }
13 
14         int[] res = new int[digits.length+1];
15         res[0] = 1;
16         return res;
17     }
18 }
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2016-06-24 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档