How to add a long integer to existing program
The code works. But, 开发者_高级运维I need to include long integers. How can I do that? I've tried a million things. I'm not good at this either so it takes me 5 times longer to get a simple code. Please help.
import java.util.Scanner;
public class Exercise2_6M
{
public static void main(String[] args)
{
// Create a Scanner
Scanner input = new Scanner(System.in);
// Enter amount
System.out.print("Enter an integer:");
int integer = input.nextInt();
// Calculations
int rinteger = Math. abs (integer);
int sum = 0;
int i=0;
while(rinteger / Math.pow(10,i) > 0)
{
sum+=getDigit(rinteger,i);
i++;
}
// Display results
System.out.println("Sum all digits in " + integer + " is " + sum);
}
public static int getDigit(int num, int power)
{
return (num % (int)Math.pow(10,power+1)) / (int)Math.pow(10,power);
}
}
Read the input value as a string and then use the BigInteger class to perform calculations with very large values.
A recursive solution can be much leaner:
import java.util.Scanner;
public class Exercise2_6M
{
public static void main (String [] args)
{
Scanner input = new Scanner (System.in);
System.out.print ("Enter an long:");
long lng = input.nextLong ();
int sum = getDigitSum (lng);
System.out.println ("Sum all digits in " + lng + " is " + sum);
}
public static int getDigitSum (long num)
{
if (num < 10L) return (int) num;
else return ((int)(num % 10)) + getDigitSum (num/10L);
}
}
精彩评论