leetcode 66:plus one

原创 2015年07月08日 13:07:01

题目:
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.
分析:
本题是将整数n的每一位存储在数组中,如n=9,则个位存入数组;n=98,个位和十位存入数组,且a[0]=9,a[1]=8,也就是最高位在数组初始位置,再执行加1操作。如果最高位需要进位,如n=99,a[0]=9,a[1]=9,加1后最高位会进位,这时候需要新建一个长度加1的数组。
代码:

public class plusOne {
    public static int[] puls(int[] digits){
        int flag=1;
        int i=0;
        for(i=digits.length-1;i>=0;i--){
            digits[i]=digits[i]+flag;
            if(digits[i]>9){
                flag=1;
                digits[i]=0;
            }else{
                return digits;
            }

        }
        if(i==-1&&flag==1){
            int[] newdigits=new int[digits.length+1];
            newdigits[0]=1;
            for(i=1;i<=digits.length;i++){
                newdigits[i]=digits[i-1];
            }
            return newdigits;
        }else{
            return digits;
        }
    }
    public static void main(String[] args){
        int[] digits={9,9};
        int[] result=puls(digits);
        for(int i=0;i<result.length;i++){
            System.out.println("i:"+i+",result:"+result[i]);
        }
    }
}
版权声明:本文为博主原创文章,未经博主允许不得转载。

LeetCode --- 66. Plus One

题目链接:Plus One Given a non-negative number represented as an array of digits, plus one to the number...
  • makuiyu
  • makuiyu
  • 2015年03月19日 21:53
  • 6588

leetcode 66. Plus One

leetcode 66. Plus One 题目大意:给定一个非负整数,存储在数组中,把这个数字加1,这个数的最高位在最前面。 解题思路:如果这个数的最低位为小于9,直接加到最低位去 如果这个数的最低...

leetcode-66. Plus One

Given a non-negative number represented as an array of digits, plus one to the number. The digits...
  • qj30212
  • qj30212
  • 2016年09月02日 00:34
  • 162

[C语言][LeetCode][66]Plus One

题目Plus One Given a non-negative number represented as an array of digits, plus one to the number. ...
  • Timsley
  • Timsley
  • 2015年08月11日 08:58
  • 1072

<LeetCode OJ> 66. Plus One

66. Plus One My Submissions Question Total Accepted: 77253 Total Submissions: 242942 Difficulty:...

LeetCode66: Plus One

Given a non-negative number represented as an array of digits, plus one to the number. The digits a...

[LeetCode] S66 Plus One

Plus One Given a non-negative number represented as an array of digits, plus one to the number. ...

LeetCode笔记:66. Plus One

用数组表示多位数字并加一

LeetCode 66 — Plus One(C++ Java Python)

题目:http://oj.leetcode.com/problems/plus-one/ Given a non-negative number represented as an arra...

Leetcode 66. Plus One

//Given a non-negative integer represented as a non-empty array of digits, plus one to the integer. ...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:leetcode 66:plus one
举报原因:
原因补充:

(最多只允许输入30个字)