Getting the individual digits of a number The 2019 Stack Overflow Developer Survey Results Are In“ChocolatesByNumbers” challengeHacker Rank: Extracting digits from a given number and check for divisibilityNecklace counting problem-with consecutive prime constraintFinding the smallest number whose digits sum to NChecking digits in a numberProject Euler #43Compute Gregorian year from given number of days since day zeroString Repeat function in VBAFaster way to loop through array of points and find if within polygonsFive functions to get the digits of a number

Carnot-Caratheodory metric

Inline version of a function returns different value then non-inline version

Geography at the pixel level

Why don't Unix/Linux systems traverse through directories until they find the required version of a linked library?

How to answer pointed "are you quitting" questioning when I don't want them to suspect

What could be the right powersource for 15 seconds lifespan disposable giant chainsaw?

Why can Shazam do this?

How can I create a character who can assume the widest possible range of creature sizes?

Dual Citizen. Exited the US on Italian passport recently

Should I use my personal or workplace e-mail when registering to external websites for work purpose?

Can we apply L'Hospital's rule where the derivative is not continuous?

Why isn't airport relocation done gradually?

Spanish for "widget"

Realistic Alternatives to Dust: What Else Could Feed a Plankton Bloom?

Is this food a bread or a loaf?

Evaluating number of iteration with a certain map with While

Can't find the latex code for the ⍎ (down tack jot) symbol

Where does the "burst of radiance" from Holy Weapon originate?

What is the best strategy for white in this position?

Is flight data recorder erased after every flight?

Could JWST stay at L2 "forever"?

Pristine Bit Checking

Why Did Howard Stark Use All The Vibranium They Had On A Prototype Shield?

Confusion about non-derivable continuous functions



Getting the individual digits of a number



The 2019 Stack Overflow Developer Survey Results Are In“ChocolatesByNumbers” challengeHacker Rank: Extracting digits from a given number and check for divisibilityNecklace counting problem-with consecutive prime constraintFinding the smallest number whose digits sum to NChecking digits in a numberProject Euler #43Compute Gregorian year from given number of days since day zeroString Repeat function in VBAFaster way to loop through array of points and find if within polygonsFive functions to get the digits of a number



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








1












$begingroup$


Approach 1:



Repeated division-modulus operations:



long num = 123456789;
int count = 0;
while(num > 0)

int digit = num % 10;
if(digit == 1)
count ++;
num /= 10;



Approach 2:



Convert it into an String and get the characters at the position:



long num = 123456789;
int count = 0;
String s = String.valueOf(num);
for(int i = 0; i < s.length(); i++)

char ch = s.charAt(i);
if(ch == '1')
count ++;



The second operation doesn't need to get the remainder and the quotient each time. A charAt() method can be enough.



Which approach is considered to be better and why?



Consider taking the input from the console.



1st Case:



long num = scanner.nextLong();


2nd Case:



String s = scanner.nextLine();


Here there would be no overhead on converting the number to string.



Also let us assume it is for positive numbers.










share|improve this question











$endgroup$











  • $begingroup$
    Welcome to CR! In what context will this be used for?
    $endgroup$
    – h.j.k.
    Jul 23 '15 at 6:38










  • $begingroup$
    Knowledge gaining context!
    $endgroup$
    – Uma Kanth
    Jul 23 '15 at 6:39










  • $begingroup$
    As in you're just interested to count the number of 1s? Would this be used in a method with the signature private static int countOccurrence(int number, int searchFor)?
    $endgroup$
    – h.j.k.
    Jul 23 '15 at 6:43










  • $begingroup$
    @h.j.k. Counting numbers is just an example. I wanted to know which would be better to get the individual digits.
    $endgroup$
    – Uma Kanth
    Jul 23 '15 at 6:44

















1












$begingroup$


Approach 1:



Repeated division-modulus operations:



long num = 123456789;
int count = 0;
while(num > 0)

int digit = num % 10;
if(digit == 1)
count ++;
num /= 10;



Approach 2:



Convert it into an String and get the characters at the position:



long num = 123456789;
int count = 0;
String s = String.valueOf(num);
for(int i = 0; i < s.length(); i++)

char ch = s.charAt(i);
if(ch == '1')
count ++;



The second operation doesn't need to get the remainder and the quotient each time. A charAt() method can be enough.



Which approach is considered to be better and why?



Consider taking the input from the console.



1st Case:



long num = scanner.nextLong();


2nd Case:



String s = scanner.nextLine();


Here there would be no overhead on converting the number to string.



Also let us assume it is for positive numbers.










share|improve this question











$endgroup$











  • $begingroup$
    Welcome to CR! In what context will this be used for?
    $endgroup$
    – h.j.k.
    Jul 23 '15 at 6:38










  • $begingroup$
    Knowledge gaining context!
    $endgroup$
    – Uma Kanth
    Jul 23 '15 at 6:39










  • $begingroup$
    As in you're just interested to count the number of 1s? Would this be used in a method with the signature private static int countOccurrence(int number, int searchFor)?
    $endgroup$
    – h.j.k.
    Jul 23 '15 at 6:43










  • $begingroup$
    @h.j.k. Counting numbers is just an example. I wanted to know which would be better to get the individual digits.
    $endgroup$
    – Uma Kanth
    Jul 23 '15 at 6:44













1












1








1


0



$begingroup$


Approach 1:



Repeated division-modulus operations:



long num = 123456789;
int count = 0;
while(num > 0)

int digit = num % 10;
if(digit == 1)
count ++;
num /= 10;



Approach 2:



Convert it into an String and get the characters at the position:



long num = 123456789;
int count = 0;
String s = String.valueOf(num);
for(int i = 0; i < s.length(); i++)

char ch = s.charAt(i);
if(ch == '1')
count ++;



The second operation doesn't need to get the remainder and the quotient each time. A charAt() method can be enough.



Which approach is considered to be better and why?



Consider taking the input from the console.



1st Case:



long num = scanner.nextLong();


2nd Case:



String s = scanner.nextLine();


Here there would be no overhead on converting the number to string.



Also let us assume it is for positive numbers.










share|improve this question











$endgroup$




Approach 1:



Repeated division-modulus operations:



long num = 123456789;
int count = 0;
while(num > 0)

int digit = num % 10;
if(digit == 1)
count ++;
num /= 10;



Approach 2:



Convert it into an String and get the characters at the position:



long num = 123456789;
int count = 0;
String s = String.valueOf(num);
for(int i = 0; i < s.length(); i++)

char ch = s.charAt(i);
if(ch == '1')
count ++;



The second operation doesn't need to get the remainder and the quotient each time. A charAt() method can be enough.



Which approach is considered to be better and why?



Consider taking the input from the console.



1st Case:



long num = scanner.nextLong();


2nd Case:



String s = scanner.nextLine();


Here there would be no overhead on converting the number to string.



Also let us assume it is for positive numbers.







java performance strings comparative-review






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jan 31 '18 at 19:04









Sᴀᴍ Onᴇᴌᴀ

10.3k62168




10.3k62168










asked Jul 23 '15 at 6:21









Uma KanthUma Kanth

119117




119117











  • $begingroup$
    Welcome to CR! In what context will this be used for?
    $endgroup$
    – h.j.k.
    Jul 23 '15 at 6:38










  • $begingroup$
    Knowledge gaining context!
    $endgroup$
    – Uma Kanth
    Jul 23 '15 at 6:39










  • $begingroup$
    As in you're just interested to count the number of 1s? Would this be used in a method with the signature private static int countOccurrence(int number, int searchFor)?
    $endgroup$
    – h.j.k.
    Jul 23 '15 at 6:43










  • $begingroup$
    @h.j.k. Counting numbers is just an example. I wanted to know which would be better to get the individual digits.
    $endgroup$
    – Uma Kanth
    Jul 23 '15 at 6:44
















  • $begingroup$
    Welcome to CR! In what context will this be used for?
    $endgroup$
    – h.j.k.
    Jul 23 '15 at 6:38










  • $begingroup$
    Knowledge gaining context!
    $endgroup$
    – Uma Kanth
    Jul 23 '15 at 6:39










  • $begingroup$
    As in you're just interested to count the number of 1s? Would this be used in a method with the signature private static int countOccurrence(int number, int searchFor)?
    $endgroup$
    – h.j.k.
    Jul 23 '15 at 6:43










  • $begingroup$
    @h.j.k. Counting numbers is just an example. I wanted to know which would be better to get the individual digits.
    $endgroup$
    – Uma Kanth
    Jul 23 '15 at 6:44















$begingroup$
Welcome to CR! In what context will this be used for?
$endgroup$
– h.j.k.
Jul 23 '15 at 6:38




$begingroup$
Welcome to CR! In what context will this be used for?
$endgroup$
– h.j.k.
Jul 23 '15 at 6:38












$begingroup$
Knowledge gaining context!
$endgroup$
– Uma Kanth
Jul 23 '15 at 6:39




$begingroup$
Knowledge gaining context!
$endgroup$
– Uma Kanth
Jul 23 '15 at 6:39












$begingroup$
As in you're just interested to count the number of 1s? Would this be used in a method with the signature private static int countOccurrence(int number, int searchFor)?
$endgroup$
– h.j.k.
Jul 23 '15 at 6:43




$begingroup$
As in you're just interested to count the number of 1s? Would this be used in a method with the signature private static int countOccurrence(int number, int searchFor)?
$endgroup$
– h.j.k.
Jul 23 '15 at 6:43












$begingroup$
@h.j.k. Counting numbers is just an example. I wanted to know which would be better to get the individual digits.
$endgroup$
– Uma Kanth
Jul 23 '15 at 6:44




$begingroup$
@h.j.k. Counting numbers is just an example. I wanted to know which would be better to get the individual digits.
$endgroup$
– Uma Kanth
Jul 23 '15 at 6:44










4 Answers
4






active

oldest

votes


















1












$begingroup$

I would suggest a third approach that extends the conversion-to-string approach: conversion to List of Character



The benefits of this is that you can utilise Java 8 collection stream feature to perform filtering, aggregation and other functions on the elements.



for instance, your example can be expressed as such (edited following @h.j.k's comment):



 long num = 123456789;
String s = String.valueOf(num);
long count = s.chars()
.mapToObj(i -> (char)i)
.filter(ch -> ch.equals('1'))
.count();





share|improve this answer











$endgroup$












  • $begingroup$
    Wells, if you really want to go down this way, then there's String.chars() that will give you an IntStream directly.
    $endgroup$
    – h.j.k.
    Jul 23 '15 at 9:46


















1












$begingroup$

This method below allows you to get a specific number from a int value based on a specific index



 public static int getSpecificNum(int number, int index) 
int numOfDigits = 0;
int pow = 1, test = 0, counter = 0;


//gets the number of digits



 while (test != number) // once the full int is retrieved
counter++;//<-digit counter
pow *= 10;
test = number % pow;//go through the entire int



// number of digits are found, reset everything



 numOfDigits = counter;
counter = 0;
pow = 1;
test = 0;


// now count until the index



 while (counter != (numOfDigits - index)) // this is numOfDigits was needed
counter++;
pow *= 10;
test = number % pow;// same thing




// exp = finding the power of 10



 int exp = numOfDigits - (index + 1);
exp = (int) Math.pow(10, exp);
return test / exp;//divide and conquer






share|improve this answer









$endgroup$




















    0












    $begingroup$

    Corner failure



    while(num > 0) ... fails to get the right count when long num = 0; and the digit sought is 0. count result is 0. I'd expect 1.



    Failure when num < 0 as int digit = num % 10; will result in a negative value.




    Oops now see in the end: "Also let us assume it is for positive numbers." Making answer wiki as a reference.



    Too bad as it is not difficult to make the code work for all int.






    share|improve this answer











    $endgroup$




















      0












      $begingroup$

      If you want to find the length of the number you don't need an array. Just using log base 10 will get you the number of places the number has so,



      long num = 1234567890;
      int length = (int) Math.log10(num); //should make the length 9


      Now to get a specific number it's



      public int getNthDigit(int number, int base, int n) 
      return (int) ((number / Math.pow(base, n - 1)) % base);



      if you enter getNthDigit(num,10,2); then it will return 2.





      share








      New contributor




      Isbees is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.






      $endgroup$













        Your Answer





        StackExchange.ifUsing("editor", function ()
        return StackExchange.using("mathjaxEditing", function ()
        StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix)
        StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
        );
        );
        , "mathjax-editing");

        StackExchange.ifUsing("editor", function ()
        StackExchange.using("externalEditor", function ()
        StackExchange.using("snippets", function ()
        StackExchange.snippets.init();
        );
        );
        , "code-snippets");

        StackExchange.ready(function()
        var channelOptions =
        tags: "".split(" "),
        id: "196"
        ;
        initTagRenderer("".split(" "), "".split(" "), channelOptions);

        StackExchange.using("externalEditor", function()
        // Have to fire editor after snippets, if snippets enabled
        if (StackExchange.settings.snippets.snippetsEnabled)
        StackExchange.using("snippets", function()
        createEditor();
        );

        else
        createEditor();

        );

        function createEditor()
        StackExchange.prepareEditor(
        heartbeatType: 'answer',
        autoActivateHeartbeat: false,
        convertImagesToLinks: false,
        noModals: true,
        showLowRepImageUploadWarning: true,
        reputationToPostImages: null,
        bindNavPrevention: true,
        postfix: "",
        imageUploader:
        brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
        contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
        allowUrls: true
        ,
        onDemand: true,
        discardSelector: ".discard-answer"
        ,immediatelyShowMarkdownHelp:true
        );



        );













        draft saved

        draft discarded


















        StackExchange.ready(
        function ()
        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f97770%2fgetting-the-individual-digits-of-a-number%23new-answer', 'question_page');

        );

        Post as a guest















        Required, but never shown

























        4 Answers
        4






        active

        oldest

        votes








        4 Answers
        4






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes









        1












        $begingroup$

        I would suggest a third approach that extends the conversion-to-string approach: conversion to List of Character



        The benefits of this is that you can utilise Java 8 collection stream feature to perform filtering, aggregation and other functions on the elements.



        for instance, your example can be expressed as such (edited following @h.j.k's comment):



         long num = 123456789;
        String s = String.valueOf(num);
        long count = s.chars()
        .mapToObj(i -> (char)i)
        .filter(ch -> ch.equals('1'))
        .count();





        share|improve this answer











        $endgroup$












        • $begingroup$
          Wells, if you really want to go down this way, then there's String.chars() that will give you an IntStream directly.
          $endgroup$
          – h.j.k.
          Jul 23 '15 at 9:46















        1












        $begingroup$

        I would suggest a third approach that extends the conversion-to-string approach: conversion to List of Character



        The benefits of this is that you can utilise Java 8 collection stream feature to perform filtering, aggregation and other functions on the elements.



        for instance, your example can be expressed as such (edited following @h.j.k's comment):



         long num = 123456789;
        String s = String.valueOf(num);
        long count = s.chars()
        .mapToObj(i -> (char)i)
        .filter(ch -> ch.equals('1'))
        .count();





        share|improve this answer











        $endgroup$












        • $begingroup$
          Wells, if you really want to go down this way, then there's String.chars() that will give you an IntStream directly.
          $endgroup$
          – h.j.k.
          Jul 23 '15 at 9:46













        1












        1








        1





        $begingroup$

        I would suggest a third approach that extends the conversion-to-string approach: conversion to List of Character



        The benefits of this is that you can utilise Java 8 collection stream feature to perform filtering, aggregation and other functions on the elements.



        for instance, your example can be expressed as such (edited following @h.j.k's comment):



         long num = 123456789;
        String s = String.valueOf(num);
        long count = s.chars()
        .mapToObj(i -> (char)i)
        .filter(ch -> ch.equals('1'))
        .count();





        share|improve this answer











        $endgroup$



        I would suggest a third approach that extends the conversion-to-string approach: conversion to List of Character



        The benefits of this is that you can utilise Java 8 collection stream feature to perform filtering, aggregation and other functions on the elements.



        for instance, your example can be expressed as such (edited following @h.j.k's comment):



         long num = 123456789;
        String s = String.valueOf(num);
        long count = s.chars()
        .mapToObj(i -> (char)i)
        .filter(ch -> ch.equals('1'))
        .count();






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Jul 23 '15 at 11:06

























        answered Jul 23 '15 at 9:38









        Sharon Ben AsherSharon Ben Asher

        2,301512




        2,301512











        • $begingroup$
          Wells, if you really want to go down this way, then there's String.chars() that will give you an IntStream directly.
          $endgroup$
          – h.j.k.
          Jul 23 '15 at 9:46
















        • $begingroup$
          Wells, if you really want to go down this way, then there's String.chars() that will give you an IntStream directly.
          $endgroup$
          – h.j.k.
          Jul 23 '15 at 9:46















        $begingroup$
        Wells, if you really want to go down this way, then there's String.chars() that will give you an IntStream directly.
        $endgroup$
        – h.j.k.
        Jul 23 '15 at 9:46




        $begingroup$
        Wells, if you really want to go down this way, then there's String.chars() that will give you an IntStream directly.
        $endgroup$
        – h.j.k.
        Jul 23 '15 at 9:46













        1












        $begingroup$

        This method below allows you to get a specific number from a int value based on a specific index



         public static int getSpecificNum(int number, int index) 
        int numOfDigits = 0;
        int pow = 1, test = 0, counter = 0;


        //gets the number of digits



         while (test != number) // once the full int is retrieved
        counter++;//<-digit counter
        pow *= 10;
        test = number % pow;//go through the entire int



        // number of digits are found, reset everything



         numOfDigits = counter;
        counter = 0;
        pow = 1;
        test = 0;


        // now count until the index



         while (counter != (numOfDigits - index)) // this is numOfDigits was needed
        counter++;
        pow *= 10;
        test = number % pow;// same thing




        // exp = finding the power of 10



         int exp = numOfDigits - (index + 1);
        exp = (int) Math.pow(10, exp);
        return test / exp;//divide and conquer






        share|improve this answer









        $endgroup$

















          1












          $begingroup$

          This method below allows you to get a specific number from a int value based on a specific index



           public static int getSpecificNum(int number, int index) 
          int numOfDigits = 0;
          int pow = 1, test = 0, counter = 0;


          //gets the number of digits



           while (test != number) // once the full int is retrieved
          counter++;//<-digit counter
          pow *= 10;
          test = number % pow;//go through the entire int



          // number of digits are found, reset everything



           numOfDigits = counter;
          counter = 0;
          pow = 1;
          test = 0;


          // now count until the index



           while (counter != (numOfDigits - index)) // this is numOfDigits was needed
          counter++;
          pow *= 10;
          test = number % pow;// same thing




          // exp = finding the power of 10



           int exp = numOfDigits - (index + 1);
          exp = (int) Math.pow(10, exp);
          return test / exp;//divide and conquer






          share|improve this answer









          $endgroup$















            1












            1








            1





            $begingroup$

            This method below allows you to get a specific number from a int value based on a specific index



             public static int getSpecificNum(int number, int index) 
            int numOfDigits = 0;
            int pow = 1, test = 0, counter = 0;


            //gets the number of digits



             while (test != number) // once the full int is retrieved
            counter++;//<-digit counter
            pow *= 10;
            test = number % pow;//go through the entire int



            // number of digits are found, reset everything



             numOfDigits = counter;
            counter = 0;
            pow = 1;
            test = 0;


            // now count until the index



             while (counter != (numOfDigits - index)) // this is numOfDigits was needed
            counter++;
            pow *= 10;
            test = number % pow;// same thing




            // exp = finding the power of 10



             int exp = numOfDigits - (index + 1);
            exp = (int) Math.pow(10, exp);
            return test / exp;//divide and conquer






            share|improve this answer









            $endgroup$



            This method below allows you to get a specific number from a int value based on a specific index



             public static int getSpecificNum(int number, int index) 
            int numOfDigits = 0;
            int pow = 1, test = 0, counter = 0;


            //gets the number of digits



             while (test != number) // once the full int is retrieved
            counter++;//<-digit counter
            pow *= 10;
            test = number % pow;//go through the entire int



            // number of digits are found, reset everything



             numOfDigits = counter;
            counter = 0;
            pow = 1;
            test = 0;


            // now count until the index



             while (counter != (numOfDigits - index)) // this is numOfDigits was needed
            counter++;
            pow *= 10;
            test = number % pow;// same thing




            // exp = finding the power of 10



             int exp = numOfDigits - (index + 1);
            exp = (int) Math.pow(10, exp);
            return test / exp;//divide and conquer







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Jan 31 '18 at 18:47









            vetrovvetrov

            111




            111





















                0












                $begingroup$

                Corner failure



                while(num > 0) ... fails to get the right count when long num = 0; and the digit sought is 0. count result is 0. I'd expect 1.



                Failure when num < 0 as int digit = num % 10; will result in a negative value.




                Oops now see in the end: "Also let us assume it is for positive numbers." Making answer wiki as a reference.



                Too bad as it is not difficult to make the code work for all int.






                share|improve this answer











                $endgroup$

















                  0












                  $begingroup$

                  Corner failure



                  while(num > 0) ... fails to get the right count when long num = 0; and the digit sought is 0. count result is 0. I'd expect 1.



                  Failure when num < 0 as int digit = num % 10; will result in a negative value.




                  Oops now see in the end: "Also let us assume it is for positive numbers." Making answer wiki as a reference.



                  Too bad as it is not difficult to make the code work for all int.






                  share|improve this answer











                  $endgroup$















                    0












                    0








                    0





                    $begingroup$

                    Corner failure



                    while(num > 0) ... fails to get the right count when long num = 0; and the digit sought is 0. count result is 0. I'd expect 1.



                    Failure when num < 0 as int digit = num % 10; will result in a negative value.




                    Oops now see in the end: "Also let us assume it is for positive numbers." Making answer wiki as a reference.



                    Too bad as it is not difficult to make the code work for all int.






                    share|improve this answer











                    $endgroup$



                    Corner failure



                    while(num > 0) ... fails to get the right count when long num = 0; and the digit sought is 0. count result is 0. I'd expect 1.



                    Failure when num < 0 as int digit = num % 10; will result in a negative value.




                    Oops now see in the end: "Also let us assume it is for positive numbers." Making answer wiki as a reference.



                    Too bad as it is not difficult to make the code work for all int.







                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    answered Jan 31 '18 at 19:52


























                    community wiki





                    chux






















                        0












                        $begingroup$

                        If you want to find the length of the number you don't need an array. Just using log base 10 will get you the number of places the number has so,



                        long num = 1234567890;
                        int length = (int) Math.log10(num); //should make the length 9


                        Now to get a specific number it's



                        public int getNthDigit(int number, int base, int n) 
                        return (int) ((number / Math.pow(base, n - 1)) % base);



                        if you enter getNthDigit(num,10,2); then it will return 2.





                        share








                        New contributor




                        Isbees is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                        Check out our Code of Conduct.






                        $endgroup$

















                          0












                          $begingroup$

                          If you want to find the length of the number you don't need an array. Just using log base 10 will get you the number of places the number has so,



                          long num = 1234567890;
                          int length = (int) Math.log10(num); //should make the length 9


                          Now to get a specific number it's



                          public int getNthDigit(int number, int base, int n) 
                          return (int) ((number / Math.pow(base, n - 1)) % base);



                          if you enter getNthDigit(num,10,2); then it will return 2.





                          share








                          New contributor




                          Isbees is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                          Check out our Code of Conduct.






                          $endgroup$















                            0












                            0








                            0





                            $begingroup$

                            If you want to find the length of the number you don't need an array. Just using log base 10 will get you the number of places the number has so,



                            long num = 1234567890;
                            int length = (int) Math.log10(num); //should make the length 9


                            Now to get a specific number it's



                            public int getNthDigit(int number, int base, int n) 
                            return (int) ((number / Math.pow(base, n - 1)) % base);



                            if you enter getNthDigit(num,10,2); then it will return 2.





                            share








                            New contributor




                            Isbees is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                            Check out our Code of Conduct.






                            $endgroup$



                            If you want to find the length of the number you don't need an array. Just using log base 10 will get you the number of places the number has so,



                            long num = 1234567890;
                            int length = (int) Math.log10(num); //should make the length 9


                            Now to get a specific number it's



                            public int getNthDigit(int number, int base, int n) 
                            return (int) ((number / Math.pow(base, n - 1)) % base);



                            if you enter getNthDigit(num,10,2); then it will return 2.






                            share








                            New contributor




                            Isbees is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                            Check out our Code of Conduct.








                            share


                            share






                            New contributor




                            Isbees is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                            Check out our Code of Conduct.









                            answered 2 mins ago









                            IsbeesIsbees

                            1




                            1




                            New contributor




                            Isbees is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                            Check out our Code of Conduct.





                            New contributor





                            Isbees is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                            Check out our Code of Conduct.






                            Isbees is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                            Check out our Code of Conduct.



























                                draft saved

                                draft discarded
















































                                Thanks for contributing an answer to Code Review Stack Exchange!


                                • Please be sure to answer the question. Provide details and share your research!

                                But avoid


                                • Asking for help, clarification, or responding to other answers.

                                • Making statements based on opinion; back them up with references or personal experience.

                                Use MathJax to format equations. MathJax reference.


                                To learn more, see our tips on writing great answers.




                                draft saved


                                draft discarded














                                StackExchange.ready(
                                function ()
                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f97770%2fgetting-the-individual-digits-of-a-number%23new-answer', 'question_page');

                                );

                                Post as a guest















                                Required, but never shown





















































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown

































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown







                                Popular posts from this blog

                                名間水力發電廠 目录 沿革 設施 鄰近設施 註釋 外部連結 导航菜单23°50′10″N 120°42′41″E / 23.83611°N 120.71139°E / 23.83611; 120.7113923°50′10″N 120°42′41″E / 23.83611°N 120.71139°E / 23.83611; 120.71139計畫概要原始内容臺灣第一座BOT 模式開發的水力發電廠-名間水力電廠名間水力發電廠 水利署首件BOT案原始内容《小檔案》名間電廠 首座BOT水力發電廠原始内容名間電廠BOT - 經濟部水利署中區水資源局

                                Prove that NP is closed under karp reduction?Space(n) not closed under Karp reductions - what about NTime(n)?Class P is closed under rotation?Prove or disprove that $NL$ is closed under polynomial many-one reductions$mathbfNC_2$ is closed under log-space reductionOn Karp reductionwhen can I know if a class (complexity) is closed under reduction (cook/karp)Check if class $PSPACE$ is closed under polyonomially space reductionIs NPSPACE also closed under polynomial-time reduction and under log-space reduction?Prove PSPACE is closed under complement?Prove PSPACE is closed under union?

                                Is my guitar’s action too high? Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern)Strings too stiff on a recently purchased acoustic guitar | Cort AD880CEIs the action of my guitar really high?Μy little finger is too weak to play guitarWith guitar, how long should I give my fingers to strengthen / callous?When playing a fret the guitar sounds mutedPlaying (Barre) chords up the guitar neckI think my guitar strings are wound too tight and I can't play barre chordsF barre chord on an SG guitarHow to find to the right strings of a barre chord by feel?High action on higher fret on my steel acoustic guitar