博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode(29)-Plus One
阅读量:7009 次
发布时间:2019-06-28

本文共 798 字,大约阅读时间需要 2 分钟。

题目:

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.

思路:

  • 题意是用一个数组来表示一个非负的整数。范围是0~9的数字,模拟一个加法的加一操作
  • 推断是否进位。假设是9,加1就是10,置为0,然后进位。
  • 假设超除了界限,又一次设置一个数组,第一位是1。后面是0 -

代码:

public class Solution {    public int[] plusOne(int[] digits) {         int carries = 1;        for(int i = digits.length-1; i>=0 && carries > 0; i--){  // fast break when carries equals zero            int sum = digits[i] + 1;            digits[i] = sum % 10;            carries = sum / 10;        }        if(carries == 0)            return digits;        int[] rst = new int[digits.length+1];        rst[0] = 1;        for(int i=1; i< rst.length; i++){            rst[i] = 0;        }        return rst;    }}

转载地址:http://kvjtl.baihongyu.com/

你可能感兴趣的文章
Jabref安装及使用教程
查看>>
结对第二次作业
查看>>
Excel 2010版筛选怎么用
查看>>
实现mypwd
查看>>
补码基础
查看>>
CF961G Partitions(第二类斯特林数)
查看>>
loj#6435. 「PKUSC2018」星际穿越(倍增)
查看>>
【Vue】IView之table组件化学习(二)
查看>>
【BZOJ 1877】 [SDOI2009]晨跑(费用流)
查看>>
django使用自己的setting的方法
查看>>
mongo explain分析详解
查看>>
why factory pattern and when to use factory pattern
查看>>
Shell 文本处理三剑客之grep
查看>>
Ubuntu安装配置TFTP服务
查看>>
用indexOf方法来去重
查看>>
vue2.x 给一个对象里添加一个没有的属性
查看>>
Codeforces C - Om Nom and Candies
查看>>
Html 笔记
查看>>
4702: 分糖果系列一
查看>>
[ARC062F]Painting Graphs with AtCoDeer
查看>>