The challenge to be solved in this post is to calculate the digit sum for any whole number. I will do it first in Python and then in Java to compare the code.
Requirements:
- Prompt the user to enter a number
- Return the digit sum for that number
Python
# digitsum1.py
def get_digitsum(number):
digitsum = sum([int(digit) for digit in number])
return digitsum
if __name__ == "__main__":
number = input("Enter a number: ")
value = get_digitsum(number)
print(value)
My first idea was to simply prompt the user for a number and store it in a variable called “number”. The contents of it will be a string of digits which is passed to the function get_digitsum.
One problem is that negative numbers are not supported. A quick fix for this is to use the abs() function to make sure we get a positive value.
# digitsum2.py
def get_digitsum(number):
digitsum = sum([int(digit) for digit in number])
return digitsum
if __name__ == "__main__":
number = str(abs(int(input("Enter a number: "))))
value = get_digitsum(number)
print(value)
Lots of nesting of functions but that’s a quick and dirty way to avoid creating variables.
So how would ChatGPT solve this? Let’s find out.
# digitsum3.py
def digitsum(n):
return sum(int(d) for d in str(abs(n)))
if __name__ == '__main__':
number = int(input("Enter a number: "))
print("Digitsum:", digitsum(number))
The logic of doing string and the absolute value is moved to the digitsum function which is something I agree is much more correct since that’s where we are doing the job of calculating the digit sum. I like having simple return statements (a single variable) so I would probably never do the logic in that statement. ChatGPT’s output is also a bit nicer printing “Digitsum: value“. Instead of creating a list comprehension, a generator object is created by not using square brackets. For this type of program, I find no preference for one over the other. ChatGPT mixes single quotes with double quotes in the example. I will stick to using double quotes only.
Combining the input from ChatGPT I would write my final program like this.
# digitsum.py
def digitsum(n):
result = sum(int(d) for d in str(abs(n)))
return result
if __name__ == "__main__":
number = int(input("Enter a number: "))
print("Digitsum:", digitsum(number))
Java
Let’s try to solve it in Java then, my experience with Java is very limited compared to Python so I expect ChatGPT to come up with a completely different solution.
I had to think for a while when doing this in Java, in order to come up with a solution. Instead of using strings as I did with Python I decided to use integers all the way through. Using the modulus operator (%) which gives the remainder of a division problem I was able to find the last digit and add it to the digitsum variable in a while loop. I also created a static method of the DigitSum class to avoid having to create an instance, similar to how Math.abs() works.
import java.util.Scanner;
class DigitSum{
static int calculate(int number) {
number = Math.abs(number);
int digitsum = 0;
do {
digitsum += number % 10;
number = number / 10;
} while(number > 0);
return digitsum;
}
}
public class DigitSumDemo {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = input.nextInt();
int sum = DigitSum.calculate(number);
System.out.println("Digitsum: " + sum);
}
}
Doing some tests it seems to work with both positive and negative numbers
Enter a number: -45532
Digitsum: 19
So how did ChatGPT solve it?
import java.util.Scanner;
public class DigitSum {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = input.nextInt();
int digitSum = 0;
if (num < 0) {
num = -num;
}
while (num > 0) {
digitSum += num % 10;
num /= 10;
}
System.out.println("Digit sum: " + digitSum);
}
}
Definitely, a more compact version using a single class, and all logic is placed in the main method. Instead of using Math.abs(), and an if statement is used to check if the number is negative. The algorithm for calculating the digit sum is the same though using the modulus operator and division by 10. ChatGPT also used the augmented division assignment operator /= which is less verbose and also consistent with the addition assignment operator which we both used.
Conclusion
I think this was a fun exercise and using chatGPT when coding can be very useful to get ideas on how to solve different problems.