Java Program for Calculating Sum of the Digits with Two Approach and time complexity

 

import java.util.Scanner;

public class DigSum {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the digit : ");
int num = sc.nextInt();

long start1 = System.nanoTime();
System.out.println("Sum is "+sumOfDigits(num));
long end1 = System.nanoTime();

System.out.println("Elapsed Time in nano seconds: "+ (end1-start1));

System.out.print("Enter the digit 2: ");
String num2 = sc.next();
long start2 = System.nanoTime();
System.out.println("Sum is "+sumOfDigitsString(num2));
long end2 = System.nanoTime();

System.out.println("Elapsed Time in nano seconds: "+ (end2-start2));


}

private static int sumOfDigitsString(String num) {
int sum = 0;
for (int i = 0; i < num.length(); i++) {
sum+= Integer.parseInt(String.valueOf(num.charAt(i)));
}
return sum;
}

public static int sumOfDigits(int digit){
int sum =0;
while (digit!=0){
int temp = digit%10;
sum+=temp;
digit = digit/10;
}
return sum;
}
}


Enter the digit : 123

Sum is 6

Elapsed Time in nano seconds: 14124942         // Using Remainder Method

Enter the digit 2: 123

Sum is 6

Elapsed Time in nano seconds: 540630            // Using String Method

Process finished with exit code 0

Comments

Popular posts from this blog

Hackerrank - Quicksort 2 - Sorting

Hackerrank - Day of the Programmer

Hackerrank - UNIQUE ARMSTRONG NUMBER