Recursively find sum of digits including negative numbersFastest way to determine if an integer's square root is an integerWay to get number of digits in an int?Finding Number of Cores in JavaHow to recursively find and list the latest modified files in a directory with subdirectories and times?How do you recursively count the number of negative numbers in an array (Java)?Recursion: Find the sum of all possible k-permutations of a given digit arrayRecursion return valuesFind Sum of Digits Using RecursionHow to recursively increment a binary number (in list form) without converting to integer?Recursion method that returns number of digits for a given integer

Can a Cauchy sequence converge for one metric while not converging for another?

Can you really stack all of this on an Opportunity Attack?

When a company launches a new product do they "come out" with a new product or do they "come up" with a new product?

How can I prevent hyper evolved versions of regular creatures from wiping out their cousins?

What are these boxed doors outside store fronts in New York?

infared filters v nd

How can I make my BBEG immortal short of making them a Lich or Vampire?

Has there ever been an airliner design involving reducing generator load by installing solar panels?

How much RAM could one put in a typical 80386 setup?

What's the point of deactivating Num Lock on login screens?

Malformed Address '10.10.21.08/24', must be X.X.X.X/NN or

How is it possible to have an ability score that is less than 3?

Can I make popcorn with any corn?

tikz convert color string to hex value

Alternative to sending password over mail?

What's that red-plus icon near a text?

Why doesn't Newton's third law mean a person bounces back to where they started when they hit the ground?

RSA: Danger of using p to create q

Replacing matching entries in one column of a file by another column from a different file

Why do I get two different answers for this counting problem?

Perform and show arithmetic with LuaLaTeX

Client team has low performances and low technical skills: we always fix their work and now they stop collaborate with us. How to solve?

NMaximize is not converging to a solution

LaTeX: Why are digits allowed in environments, but forbidden in commands?



Recursively find sum of digits including negative numbers


Fastest way to determine if an integer's square root is an integerWay to get number of digits in an int?Finding Number of Cores in JavaHow to recursively find and list the latest modified files in a directory with subdirectories and times?How do you recursively count the number of negative numbers in an array (Java)?Recursion: Find the sum of all possible k-permutations of a given digit arrayRecursion return valuesFind Sum of Digits Using RecursionHow to recursively increment a binary number (in list form) without converting to integer?Recursion method that returns number of digits for a given integer






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








1















I'm working on a few challenges using recursion in Java (a new concept to me). I'm currently working on a recursive method that gives the sum of digits given a long parameter (n). Intended output:



  • 257 = 14

  • -257 = -14

I've tried editing my base case to include the numbers only between 1 & 10, then decrement the sum for sumOfDigits(), but obviously you cannot use an if, else if, or else statement in a recursive method. I am stuck! Can someone steer me towards the solution? Here's my method:



 public static long sumOfDigits(long n)

long sum = n %10;
if ( n < 10)
return sum;
else
return sum += sumOfDigits(n%10);











share|improve this question
























  • Why can you not use if, else if and else statements in a recursive method?

    – OptimusCrime
    Mar 9 at 1:08






  • 1





    You are correct, thanks for your comment! You made me do some more digging and I solved my own problem.

    – Sam Matthews
    Mar 9 at 1:23

















1















I'm working on a few challenges using recursion in Java (a new concept to me). I'm currently working on a recursive method that gives the sum of digits given a long parameter (n). Intended output:



  • 257 = 14

  • -257 = -14

I've tried editing my base case to include the numbers only between 1 & 10, then decrement the sum for sumOfDigits(), but obviously you cannot use an if, else if, or else statement in a recursive method. I am stuck! Can someone steer me towards the solution? Here's my method:



 public static long sumOfDigits(long n)

long sum = n %10;
if ( n < 10)
return sum;
else
return sum += sumOfDigits(n%10);











share|improve this question
























  • Why can you not use if, else if and else statements in a recursive method?

    – OptimusCrime
    Mar 9 at 1:08






  • 1





    You are correct, thanks for your comment! You made me do some more digging and I solved my own problem.

    – Sam Matthews
    Mar 9 at 1:23













1












1








1


1






I'm working on a few challenges using recursion in Java (a new concept to me). I'm currently working on a recursive method that gives the sum of digits given a long parameter (n). Intended output:



  • 257 = 14

  • -257 = -14

I've tried editing my base case to include the numbers only between 1 & 10, then decrement the sum for sumOfDigits(), but obviously you cannot use an if, else if, or else statement in a recursive method. I am stuck! Can someone steer me towards the solution? Here's my method:



 public static long sumOfDigits(long n)

long sum = n %10;
if ( n < 10)
return sum;
else
return sum += sumOfDigits(n%10);











share|improve this question
















I'm working on a few challenges using recursion in Java (a new concept to me). I'm currently working on a recursive method that gives the sum of digits given a long parameter (n). Intended output:



  • 257 = 14

  • -257 = -14

I've tried editing my base case to include the numbers only between 1 & 10, then decrement the sum for sumOfDigits(), but obviously you cannot use an if, else if, or else statement in a recursive method. I am stuck! Can someone steer me towards the solution? Here's my method:



 public static long sumOfDigits(long n)

long sum = n %10;
if ( n < 10)
return sum;
else
return sum += sumOfDigits(n%10);








java recursion






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 9 at 4:17









cdlane

19.9k21245




19.9k21245










asked Mar 9 at 1:05









Sam MatthewsSam Matthews

208




208












  • Why can you not use if, else if and else statements in a recursive method?

    – OptimusCrime
    Mar 9 at 1:08






  • 1





    You are correct, thanks for your comment! You made me do some more digging and I solved my own problem.

    – Sam Matthews
    Mar 9 at 1:23

















  • Why can you not use if, else if and else statements in a recursive method?

    – OptimusCrime
    Mar 9 at 1:08






  • 1





    You are correct, thanks for your comment! You made me do some more digging and I solved my own problem.

    – Sam Matthews
    Mar 9 at 1:23
















Why can you not use if, else if and else statements in a recursive method?

– OptimusCrime
Mar 9 at 1:08





Why can you not use if, else if and else statements in a recursive method?

– OptimusCrime
Mar 9 at 1:08




1




1





You are correct, thanks for your comment! You made me do some more digging and I solved my own problem.

– Sam Matthews
Mar 9 at 1:23





You are correct, thanks for your comment! You made me do some more digging and I solved my own problem.

– Sam Matthews
Mar 9 at 1:23












3 Answers
3






active

oldest

votes


















1














For anyone wondering, I managed to solve this myself!
Solution:



public static long sumOfDigits(long n)

long sum = n %10;

if (n == 0) return 0;

if ( n >= 1 && n < 10)
return sum;
else if (n < 0)
return sum - sumOfDigits(-n %10);
else
return sum + sumOfDigits(n%10);







share|improve this answer

























  • This works by coincidence, not by design. It simply returns twice the last digit. But since the last digit of test number 257 equals the sum of the first two digits, it appears to work. Change the test number from 257 to 256 and instead of getting 13, you'll get 12 -- the last digit doubled. Who upvoted this?

    – cdlane
    Mar 9 at 4:00



















1














I believe the solution is simpler than folks are trying to make it:



public static long sumOfDigits(long n) 

long digit = n % 10;

if (n == digit)
return n;


return digit + sumOfDigits(n / 10);



The sum in the return statement is independent of sign as you're either adding positives to positive or negatives to negatives.



The tricky part is the digit extraction and test -- it depends on Java's remainder operator (%) preserving the sign of the number on the left. In some languages (e.g. Python) this is a modulus operator that always returns a positive result. If you're working with a language with modulus, which doesn't preserve sign, you'll need a workaround for this (e.g. the abs() and/or sign() functions).






share|improve this answer
































    0














    You can do it like this:



    public class SumOfDigits 

    public static void main(String[] args)
    System.out.println("257 -> " + sumOfDigits(257));
    System.out.println("-257 -> " + sumOfDigits(-257));
    System.out.println("0 -> " + sumOfDigits(0));
    System.out.println("1 -> " + sumOfDigits(1));


    public static long sumOfDigits(long n)
    if (n < 0)
    return sumOfDigitsOfPositive(Math.abs(n)) * -1;

    else
    return sumOfDigitsOfPositive(n);



    // Parameter n must be positive
    private static long sumOfDigitsOfPositive(long n)
    if (n < 10)
    return n;

    else
    long lastDigit = n % 10;
    return lastDigit + sumOfDigitsOfPositive(n / 10);








    share|improve this answer























      Your Answer






      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: "1"
      ;
      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: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      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%2fstackoverflow.com%2fquestions%2f55073001%2frecursively-find-sum-of-digits-including-negative-numbers%23new-answer', 'question_page');

      );

      Post as a guest















      Required, but never shown

























      3 Answers
      3






      active

      oldest

      votes








      3 Answers
      3






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      1














      For anyone wondering, I managed to solve this myself!
      Solution:



      public static long sumOfDigits(long n)

      long sum = n %10;

      if (n == 0) return 0;

      if ( n >= 1 && n < 10)
      return sum;
      else if (n < 0)
      return sum - sumOfDigits(-n %10);
      else
      return sum + sumOfDigits(n%10);







      share|improve this answer

























      • This works by coincidence, not by design. It simply returns twice the last digit. But since the last digit of test number 257 equals the sum of the first two digits, it appears to work. Change the test number from 257 to 256 and instead of getting 13, you'll get 12 -- the last digit doubled. Who upvoted this?

        – cdlane
        Mar 9 at 4:00
















      1














      For anyone wondering, I managed to solve this myself!
      Solution:



      public static long sumOfDigits(long n)

      long sum = n %10;

      if (n == 0) return 0;

      if ( n >= 1 && n < 10)
      return sum;
      else if (n < 0)
      return sum - sumOfDigits(-n %10);
      else
      return sum + sumOfDigits(n%10);







      share|improve this answer

























      • This works by coincidence, not by design. It simply returns twice the last digit. But since the last digit of test number 257 equals the sum of the first two digits, it appears to work. Change the test number from 257 to 256 and instead of getting 13, you'll get 12 -- the last digit doubled. Who upvoted this?

        – cdlane
        Mar 9 at 4:00














      1












      1








      1







      For anyone wondering, I managed to solve this myself!
      Solution:



      public static long sumOfDigits(long n)

      long sum = n %10;

      if (n == 0) return 0;

      if ( n >= 1 && n < 10)
      return sum;
      else if (n < 0)
      return sum - sumOfDigits(-n %10);
      else
      return sum + sumOfDigits(n%10);







      share|improve this answer















      For anyone wondering, I managed to solve this myself!
      Solution:



      public static long sumOfDigits(long n)

      long sum = n %10;

      if (n == 0) return 0;

      if ( n >= 1 && n < 10)
      return sum;
      else if (n < 0)
      return sum - sumOfDigits(-n %10);
      else
      return sum + sumOfDigits(n%10);








      share|improve this answer














      share|improve this answer



      share|improve this answer








      edited Mar 9 at 3:03

























      answered Mar 9 at 1:24









      Sam MatthewsSam Matthews

      208




      208












      • This works by coincidence, not by design. It simply returns twice the last digit. But since the last digit of test number 257 equals the sum of the first two digits, it appears to work. Change the test number from 257 to 256 and instead of getting 13, you'll get 12 -- the last digit doubled. Who upvoted this?

        – cdlane
        Mar 9 at 4:00


















      • This works by coincidence, not by design. It simply returns twice the last digit. But since the last digit of test number 257 equals the sum of the first two digits, it appears to work. Change the test number from 257 to 256 and instead of getting 13, you'll get 12 -- the last digit doubled. Who upvoted this?

        – cdlane
        Mar 9 at 4:00

















      This works by coincidence, not by design. It simply returns twice the last digit. But since the last digit of test number 257 equals the sum of the first two digits, it appears to work. Change the test number from 257 to 256 and instead of getting 13, you'll get 12 -- the last digit doubled. Who upvoted this?

      – cdlane
      Mar 9 at 4:00






      This works by coincidence, not by design. It simply returns twice the last digit. But since the last digit of test number 257 equals the sum of the first two digits, it appears to work. Change the test number from 257 to 256 and instead of getting 13, you'll get 12 -- the last digit doubled. Who upvoted this?

      – cdlane
      Mar 9 at 4:00














      1














      I believe the solution is simpler than folks are trying to make it:



      public static long sumOfDigits(long n) 

      long digit = n % 10;

      if (n == digit)
      return n;


      return digit + sumOfDigits(n / 10);



      The sum in the return statement is independent of sign as you're either adding positives to positive or negatives to negatives.



      The tricky part is the digit extraction and test -- it depends on Java's remainder operator (%) preserving the sign of the number on the left. In some languages (e.g. Python) this is a modulus operator that always returns a positive result. If you're working with a language with modulus, which doesn't preserve sign, you'll need a workaround for this (e.g. the abs() and/or sign() functions).






      share|improve this answer





























        1














        I believe the solution is simpler than folks are trying to make it:



        public static long sumOfDigits(long n) 

        long digit = n % 10;

        if (n == digit)
        return n;


        return digit + sumOfDigits(n / 10);



        The sum in the return statement is independent of sign as you're either adding positives to positive or negatives to negatives.



        The tricky part is the digit extraction and test -- it depends on Java's remainder operator (%) preserving the sign of the number on the left. In some languages (e.g. Python) this is a modulus operator that always returns a positive result. If you're working with a language with modulus, which doesn't preserve sign, you'll need a workaround for this (e.g. the abs() and/or sign() functions).






        share|improve this answer



























          1












          1








          1







          I believe the solution is simpler than folks are trying to make it:



          public static long sumOfDigits(long n) 

          long digit = n % 10;

          if (n == digit)
          return n;


          return digit + sumOfDigits(n / 10);



          The sum in the return statement is independent of sign as you're either adding positives to positive or negatives to negatives.



          The tricky part is the digit extraction and test -- it depends on Java's remainder operator (%) preserving the sign of the number on the left. In some languages (e.g. Python) this is a modulus operator that always returns a positive result. If you're working with a language with modulus, which doesn't preserve sign, you'll need a workaround for this (e.g. the abs() and/or sign() functions).






          share|improve this answer















          I believe the solution is simpler than folks are trying to make it:



          public static long sumOfDigits(long n) 

          long digit = n % 10;

          if (n == digit)
          return n;


          return digit + sumOfDigits(n / 10);



          The sum in the return statement is independent of sign as you're either adding positives to positive or negatives to negatives.



          The tricky part is the digit extraction and test -- it depends on Java's remainder operator (%) preserving the sign of the number on the left. In some languages (e.g. Python) this is a modulus operator that always returns a positive result. If you're working with a language with modulus, which doesn't preserve sign, you'll need a workaround for this (e.g. the abs() and/or sign() functions).







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Mar 9 at 5:04

























          answered Mar 9 at 4:11









          cdlanecdlane

          19.9k21245




          19.9k21245





















              0














              You can do it like this:



              public class SumOfDigits 

              public static void main(String[] args)
              System.out.println("257 -> " + sumOfDigits(257));
              System.out.println("-257 -> " + sumOfDigits(-257));
              System.out.println("0 -> " + sumOfDigits(0));
              System.out.println("1 -> " + sumOfDigits(1));


              public static long sumOfDigits(long n)
              if (n < 0)
              return sumOfDigitsOfPositive(Math.abs(n)) * -1;

              else
              return sumOfDigitsOfPositive(n);



              // Parameter n must be positive
              private static long sumOfDigitsOfPositive(long n)
              if (n < 10)
              return n;

              else
              long lastDigit = n % 10;
              return lastDigit + sumOfDigitsOfPositive(n / 10);








              share|improve this answer



























                0














                You can do it like this:



                public class SumOfDigits 

                public static void main(String[] args)
                System.out.println("257 -> " + sumOfDigits(257));
                System.out.println("-257 -> " + sumOfDigits(-257));
                System.out.println("0 -> " + sumOfDigits(0));
                System.out.println("1 -> " + sumOfDigits(1));


                public static long sumOfDigits(long n)
                if (n < 0)
                return sumOfDigitsOfPositive(Math.abs(n)) * -1;

                else
                return sumOfDigitsOfPositive(n);



                // Parameter n must be positive
                private static long sumOfDigitsOfPositive(long n)
                if (n < 10)
                return n;

                else
                long lastDigit = n % 10;
                return lastDigit + sumOfDigitsOfPositive(n / 10);








                share|improve this answer

























                  0












                  0








                  0







                  You can do it like this:



                  public class SumOfDigits 

                  public static void main(String[] args)
                  System.out.println("257 -> " + sumOfDigits(257));
                  System.out.println("-257 -> " + sumOfDigits(-257));
                  System.out.println("0 -> " + sumOfDigits(0));
                  System.out.println("1 -> " + sumOfDigits(1));


                  public static long sumOfDigits(long n)
                  if (n < 0)
                  return sumOfDigitsOfPositive(Math.abs(n)) * -1;

                  else
                  return sumOfDigitsOfPositive(n);



                  // Parameter n must be positive
                  private static long sumOfDigitsOfPositive(long n)
                  if (n < 10)
                  return n;

                  else
                  long lastDigit = n % 10;
                  return lastDigit + sumOfDigitsOfPositive(n / 10);








                  share|improve this answer













                  You can do it like this:



                  public class SumOfDigits 

                  public static void main(String[] args)
                  System.out.println("257 -> " + sumOfDigits(257));
                  System.out.println("-257 -> " + sumOfDigits(-257));
                  System.out.println("0 -> " + sumOfDigits(0));
                  System.out.println("1 -> " + sumOfDigits(1));


                  public static long sumOfDigits(long n)
                  if (n < 0)
                  return sumOfDigitsOfPositive(Math.abs(n)) * -1;

                  else
                  return sumOfDigitsOfPositive(n);



                  // Parameter n must be positive
                  private static long sumOfDigitsOfPositive(long n)
                  if (n < 10)
                  return n;

                  else
                  long lastDigit = n % 10;
                  return lastDigit + sumOfDigitsOfPositive(n / 10);









                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Mar 9 at 3:04









                  Prasad KarunagodaPrasad Karunagoda

                  1,7532814




                  1,7532814



























                      draft saved

                      draft discarded
















































                      Thanks for contributing an answer to Stack Overflow!


                      • 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.

                      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%2fstackoverflow.com%2fquestions%2f55073001%2frecursively-find-sum-of-digits-including-negative-numbers%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

                      Can't initialize raids on a new ASUS Prime B360M-A motherboard2019 Community Moderator ElectionSimilar to RAID config yet more like mirroring solution?Can't get motherboard serial numberWhy does the BIOS entry point start with a WBINVD instruction?UEFI performance Asus Maximus V Extreme

                      Identity Server 4 is not redirecting to Angular app after login2019 Community Moderator ElectionIdentity Server 4 and dockerIdentityserver implicit flow unauthorized_clientIdentityServer Hybrid Flow - Access Token is null after user successful loginIdentity Server to MVC client : Page Redirect After loginLogin with Steam OpenId(oidc-client-js)Identity Server 4+.NET Core 2.0 + IdentityIdentityServer4 post-login redirect not working in Edge browserCall to IdentityServer4 generates System.NullReferenceException: Object reference not set to an instance of an objectIdentityServer4 without HTTPS not workingHow to get Authorization code from identity server without login form

                      2005 Ahvaz unrest Contents Background Causes Casualties Aftermath See also References Navigation menue"At Least 10 Are Killed by Bombs in Iran""Iran"Archived"Arab-Iranians in Iran to make April 15 'Day of Fury'"State of Mind, State of Order: Reactions to Ethnic Unrest in the Islamic Republic of Iran.10.1111/j.1754-9469.2008.00028.x"Iran hangs Arab separatists"Iran Overview from ArchivedConstitution of the Islamic Republic of Iran"Tehran puzzled by forged 'riots' letter""Iran and its minorities: Down in the second class""Iran: Handling Of Ahvaz Unrest Could End With Televised Confessions""Bombings Rock Iran Ahead of Election""Five die in Iran ethnic clashes""Iran: Need for restraint as anniversary of unrest in Khuzestan approaches"Archived"Iranian Sunni protesters killed in clashes with security forces"Archived