LeetCode Problem 66 : Plus One












1












$begingroup$


I have started practicing problems in leetcode and I solved the following problem on LeetCode.



The challenge is :




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



The digits are stored such that the most significant digit is at the head of the list, and each element in the array contain a single digit.



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




 Example 1:
Input: [1,2,3]
Output: [1,2,4]
Explanation: The array represents the integer 123.

Example 2:
Input: [4,3,2,1]
Output: [4,3,2,2]
Explanation: The array represents the integer 4321.


I am trying to get better at writing good code for my solutions. Please give me your suggestions



class Solution {
public int plusOne(int a) {


int length = a.length-1;

while(length>=0)
{
a[length]=a[length]+1;
int carry = a[length]/10;
if(carry==1)
{
a[length]=0;
length=length-1;
}
else
break;
}

if(a[0]==0)
{
int array = new int[a.length+1];
array[0]=1;
for(int i=1;i<array.length-1;i++)
{
array[i]=0;
}
return array;
}
return a;

}
}









share|improve this question











$endgroup$

















    1












    $begingroup$


    I have started practicing problems in leetcode and I solved the following problem on LeetCode.



    The challenge is :




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



    The digits are stored such that the most significant digit is at the head of the list, and each element in the array contain a single digit.



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




     Example 1:
    Input: [1,2,3]
    Output: [1,2,4]
    Explanation: The array represents the integer 123.

    Example 2:
    Input: [4,3,2,1]
    Output: [4,3,2,2]
    Explanation: The array represents the integer 4321.


    I am trying to get better at writing good code for my solutions. Please give me your suggestions



    class Solution {
    public int plusOne(int a) {


    int length = a.length-1;

    while(length>=0)
    {
    a[length]=a[length]+1;
    int carry = a[length]/10;
    if(carry==1)
    {
    a[length]=0;
    length=length-1;
    }
    else
    break;
    }

    if(a[0]==0)
    {
    int array = new int[a.length+1];
    array[0]=1;
    for(int i=1;i<array.length-1;i++)
    {
    array[i]=0;
    }
    return array;
    }
    return a;

    }
    }









    share|improve this question











    $endgroup$















      1












      1








      1





      $begingroup$


      I have started practicing problems in leetcode and I solved the following problem on LeetCode.



      The challenge is :




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



      The digits are stored such that the most significant digit is at the head of the list, and each element in the array contain a single digit.



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




       Example 1:
      Input: [1,2,3]
      Output: [1,2,4]
      Explanation: The array represents the integer 123.

      Example 2:
      Input: [4,3,2,1]
      Output: [4,3,2,2]
      Explanation: The array represents the integer 4321.


      I am trying to get better at writing good code for my solutions. Please give me your suggestions



      class Solution {
      public int plusOne(int a) {


      int length = a.length-1;

      while(length>=0)
      {
      a[length]=a[length]+1;
      int carry = a[length]/10;
      if(carry==1)
      {
      a[length]=0;
      length=length-1;
      }
      else
      break;
      }

      if(a[0]==0)
      {
      int array = new int[a.length+1];
      array[0]=1;
      for(int i=1;i<array.length-1;i++)
      {
      array[i]=0;
      }
      return array;
      }
      return a;

      }
      }









      share|improve this question











      $endgroup$




      I have started practicing problems in leetcode and I solved the following problem on LeetCode.



      The challenge is :




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



      The digits are stored such that the most significant digit is at the head of the list, and each element in the array contain a single digit.



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




       Example 1:
      Input: [1,2,3]
      Output: [1,2,4]
      Explanation: The array represents the integer 123.

      Example 2:
      Input: [4,3,2,1]
      Output: [4,3,2,2]
      Explanation: The array represents the integer 4321.


      I am trying to get better at writing good code for my solutions. Please give me your suggestions



      class Solution {
      public int plusOne(int a) {


      int length = a.length-1;

      while(length>=0)
      {
      a[length]=a[length]+1;
      int carry = a[length]/10;
      if(carry==1)
      {
      a[length]=0;
      length=length-1;
      }
      else
      break;
      }

      if(a[0]==0)
      {
      int array = new int[a.length+1];
      array[0]=1;
      for(int i=1;i<array.length-1;i++)
      {
      array[i]=0;
      }
      return array;
      }
      return a;

      }
      }






      java programming-challenge






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited 6 hours ago









      Sᴀᴍ Onᴇᴌᴀ

      9,55562164




      9,55562164










      asked 7 hours ago









      Dhrubojyoti BhattacharjeeDhrubojyoti Bhattacharjee

      14618




      14618






















          1 Answer
          1






          active

          oldest

          votes


















          0












          $begingroup$

          The way you handle the extra digit for the last carry seems clumsy to me. To my mind, it would be much better to include the extra digit, by creating a new array at the start, then discard the extra digit if it's not needed.



          Having that array for the answer, allows you to use it to hold the carry if needed.



          When you know the numeric limits to your loop, it is much better to use a for loop rather than a while loop. This keeps the relative information for the loop in one place.



          Putting this together it could look like this:



          public int plusOne(int digits) {
          int newLength = digits[0] == 9 ? digits.length + 1 : digits.length;
          int answer = new int[newLength];
          int a = newLength - 1;
          answer[a] = 1;
          for (int d = digits.length - 1; d >= 0; --d, --a) {
          answer[a] += digits[d];
          if (answer[a] == 10) {
          answer[a] = 0;
          answer[a-1] = 1;
          }
          }
          return answer[0] > 0 ? answer : Arrays.copyOfRange(answer, 1, newLength);
          }





          share|improve this answer









          $endgroup$













            Your Answer





            StackExchange.ifUsing("editor", function () {
            return StackExchange.using("mathjaxEditing", function () {
            StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
            StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
            });
            });
            }, "mathjax-editing");

            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "196"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: false,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: null,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f213407%2fleetcode-problem-66-plus-one%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            0












            $begingroup$

            The way you handle the extra digit for the last carry seems clumsy to me. To my mind, it would be much better to include the extra digit, by creating a new array at the start, then discard the extra digit if it's not needed.



            Having that array for the answer, allows you to use it to hold the carry if needed.



            When you know the numeric limits to your loop, it is much better to use a for loop rather than a while loop. This keeps the relative information for the loop in one place.



            Putting this together it could look like this:



            public int plusOne(int digits) {
            int newLength = digits[0] == 9 ? digits.length + 1 : digits.length;
            int answer = new int[newLength];
            int a = newLength - 1;
            answer[a] = 1;
            for (int d = digits.length - 1; d >= 0; --d, --a) {
            answer[a] += digits[d];
            if (answer[a] == 10) {
            answer[a] = 0;
            answer[a-1] = 1;
            }
            }
            return answer[0] > 0 ? answer : Arrays.copyOfRange(answer, 1, newLength);
            }





            share|improve this answer









            $endgroup$


















              0












              $begingroup$

              The way you handle the extra digit for the last carry seems clumsy to me. To my mind, it would be much better to include the extra digit, by creating a new array at the start, then discard the extra digit if it's not needed.



              Having that array for the answer, allows you to use it to hold the carry if needed.



              When you know the numeric limits to your loop, it is much better to use a for loop rather than a while loop. This keeps the relative information for the loop in one place.



              Putting this together it could look like this:



              public int plusOne(int digits) {
              int newLength = digits[0] == 9 ? digits.length + 1 : digits.length;
              int answer = new int[newLength];
              int a = newLength - 1;
              answer[a] = 1;
              for (int d = digits.length - 1; d >= 0; --d, --a) {
              answer[a] += digits[d];
              if (answer[a] == 10) {
              answer[a] = 0;
              answer[a-1] = 1;
              }
              }
              return answer[0] > 0 ? answer : Arrays.copyOfRange(answer, 1, newLength);
              }





              share|improve this answer









              $endgroup$
















                0












                0








                0





                $begingroup$

                The way you handle the extra digit for the last carry seems clumsy to me. To my mind, it would be much better to include the extra digit, by creating a new array at the start, then discard the extra digit if it's not needed.



                Having that array for the answer, allows you to use it to hold the carry if needed.



                When you know the numeric limits to your loop, it is much better to use a for loop rather than a while loop. This keeps the relative information for the loop in one place.



                Putting this together it could look like this:



                public int plusOne(int digits) {
                int newLength = digits[0] == 9 ? digits.length + 1 : digits.length;
                int answer = new int[newLength];
                int a = newLength - 1;
                answer[a] = 1;
                for (int d = digits.length - 1; d >= 0; --d, --a) {
                answer[a] += digits[d];
                if (answer[a] == 10) {
                answer[a] = 0;
                answer[a-1] = 1;
                }
                }
                return answer[0] > 0 ? answer : Arrays.copyOfRange(answer, 1, newLength);
                }





                share|improve this answer









                $endgroup$



                The way you handle the extra digit for the last carry seems clumsy to me. To my mind, it would be much better to include the extra digit, by creating a new array at the start, then discard the extra digit if it's not needed.



                Having that array for the answer, allows you to use it to hold the carry if needed.



                When you know the numeric limits to your loop, it is much better to use a for loop rather than a while loop. This keeps the relative information for the loop in one place.



                Putting this together it could look like this:



                public int plusOne(int digits) {
                int newLength = digits[0] == 9 ? digits.length + 1 : digits.length;
                int answer = new int[newLength];
                int a = newLength - 1;
                answer[a] = 1;
                for (int d = digits.length - 1; d >= 0; --d, --a) {
                answer[a] += digits[d];
                if (answer[a] == 10) {
                answer[a] = 0;
                answer[a-1] = 1;
                }
                }
                return answer[0] > 0 ? answer : Arrays.copyOfRange(answer, 1, newLength);
                }






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered 5 hours ago









                tinstaafltinstaafl

                6,7081928




                6,7081928






























                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Code Review Stack Exchange!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    Use MathJax to format equations. MathJax reference.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f213407%2fleetcode-problem-66-plus-one%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    How to make a Squid Proxy server?

                    Is this a new Fibonacci Identity?

                    19世紀