Don’t worry, unlock all articles / blogs on PrepInsta by just simply logging in on our website
Java Program to print sum of all odd digits present in a larger number
August 20, 2021
Sum of all odd digits of a Number
Java program to print sum of all odd digits of a larger number is being explained in this article. Sum of all odd digits can be found by separating each digit from the number and checking whether the digit is odd or not, if odd then add that digit.
Sample Input : 1234567
Sample Output : 16
Approach
Step 1: Take a long number as input from the user.
Step 2: Extract a single digit from a number.
Step 3: Check if digit is odd or not.
Step 4: If digit is odd, then add the digit to variable sum.
Step 5: Print the sum.
Code in Java
import java.util.*; class Solution { public static void main(String[] args) { Scanner sc=new Scanner(System.in); long no=sc.nextLong(); long sum=0; while(no>0) { if((no%10)%2!=0) sum=sum+no%10; no=no/10; } System.out.println(sum); } }
Login/Signup to comment