Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,569 questions

56,787 answers

573 users

How to get the Nth digit of a number in Java

2 Answers

0 votes
public class MyClass {
    public static void main(String args[]) {
        int number = 873591;
        String s = String.valueOf(number);
        int N = 4;
        
        char ch = s.charAt(N - 1);
        System.out.println(ch);
        
        int x = s.charAt(N - 1) - '0';
        System.out.println(x);
    }
}



/*
run:

5
5

*/

 



answered Jun 1, 2020 by avibootz
0 votes
/**
 * Utility class for digit-related operations.
 */
public final class NumberUtils {

    private NumberUtils() {
        // Prevent instantiation of utility class.
    }

    /**
     * Returns the N-th digit of a number, counting from the left.
     *
     * Examples:
     * number = 12745
     * position = 1 -> 1
     * position = 3 -> 7
     *
     * @param number   The input number.
     * @param position The digit position (1-based, from the left).
     * @return The digit at the specified position.
     * @throws IllegalArgumentException If position is out of range.
     */
    public static int getDigitFromLeft(long number, int position) {
        String digits = Long.toString(Math.abs(number));
    
        if (position < 1 || position > digits.length()) {
            throw new IllegalArgumentException(
                "Position is out of range."
            );
        }
    
        return digits.charAt(position - 1) - '0';
    }

    public static void main(String[] args) {
        long number = 12745;

        System.out.println(getDigitFromLeft(number, 1)); 
        System.out.println(getDigitFromLeft(number, 3)); 
        System.out.println(getDigitFromLeft(number, 5)); 
    }
}



/*
run:

1
7
5

*/

 



answered 3 days ago by avibootz
...