xxxxxxxxxx
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int num = input.nextInt();
int count = 0;
while (num > 0) {
num /= 10;
count++;
}
System.out.println("number of digits: " + count);
}
xxxxxxxxxx
int n = 1000;
int length = (int)(Math.log10(n)+1);
//NB: only valid for n > 0
xxxxxxxxxx
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int num = input.nextInt();
int sum = 0;
while (num > 0) {
sum += num % 10;
num /= 10;
}
System.out.println("sum of digits: " + sum);
}
xxxxxxxxxx
Scanner sc = new Scanner(System.in);
System.out.println(" enter a number ");
int n=sc.nextInt();
int sum =0;
do{
n=n/10;
sum+=1;
}while(n!=0);
System.out.println(sum);
}
xxxxxxxxxx
import java.util.*;
public class tUf {
static int count_digits(int n)
{
int digits = (int) Math.floor(Math.log10(n) + 1);
return digits;
}
public static void main(String args[])
{
int n = 12345;
System.out.println("Number of digits in "+n+" is "+count_digits(n));
}
}
xxxxxxxxxx
public class Main {
public static void main(String[] args) {
int number = 98765;
int digitIndex = 3; // The index of the digit to be extracted, starting from right (0-indexed)
int digit = getDigit(number, digitIndex);
System.out.println("The digit at index " + digitIndex + " is: " + digit);
}
public static int getDigit(int number, int digitIndex) {
// Convert the number to a string
String numberString = String.valueOf(number);
// Get the index of the digit from the right
int reversedIndex = numberString.length() - 1 - digitIndex;
// Extract the digit at the given index
char digitChar = numberString.charAt(reversedIndex);
// Convert the digit character to an integer and return it
return Character.getNumericValue(digitChar);
}
}