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;
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
add a comment |
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
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
add a comment |
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
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
java recursion
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
add a comment |
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
add a comment |
3 Answers
3
active
oldest
votes
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);
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
add a comment |
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).
add a comment |
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);
add a comment |
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
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
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);
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
add a comment |
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);
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
add a comment |
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);
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);
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
add a comment |
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
add a comment |
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).
add a comment |
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).
add a comment |
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).
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).
edited Mar 9 at 5:04
answered Mar 9 at 4:11
cdlanecdlane
19.9k21245
19.9k21245
add a comment |
add a comment |
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);
add a comment |
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);
add a comment |
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);
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);
answered Mar 9 at 3:04
Prasad KarunagodaPrasad Karunagoda
1,7532814
1,7532814
add a comment |
add a comment |
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.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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
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