Parth
Parth

Reputation: 265

Way to get number of digits from a long using Modulos

My ta told me that if i want to count the length of a long variable I can create a method using modulos. From what I understood he was saying that i need to keep using modulos until the long is 0. Here's what I'm thinking right now, but i'm pretty lost.

public static int inputSize(long cc_num)
{
  int count = 0;
  while( cc_num > 0) 
    {
     count += 1;
     cc_num = cc_num % 10;
    }
}

Upvotes: 1

Views: 509

Answers (3)

samgak
samgak

Reputation: 24417

If you want to limit the number of possible comparisons:

public static int inputSize(long cc_num)
{
    if(cc_num < 0)  // check for negative numbers
       cc_num = -cc_num;
    int count = 1;
    if(cc_num >= 10000000000000000L)
    {
        count += 16;
        cc_num /= 10000000000000000L;
    }
    if(cc_num >= 100000000)
    {
        count += 8;
        cc_num /= 100000000;
    }
    if(cc_num >= 10000)
    {
        count += 4;
        cc_num /= 10000;
    }
    if(cc_num >= 100)
    {
        count += 2;
        cc_num /= 100;
    }
    if(cc_num >= 10)
    {
        count ++;
    }
    return count;
}

Upvotes: 0

MaxZoom
MaxZoom

Reputation: 7753

Here is your code with minor changes:

public static boolean validSize(long cc_num) {
  int count = 0;
  if (cc_num < 0)  cc_num *= -1; // fix negative number

  while (cc_num > 0) {
    count++;
    cc_num = cc_num / 10;
  }

  //checks if length of long is correct
  return count == 15 || count == 16;
}

Let me know if this works for you.

Upvotes: 0

OmriP
OmriP

Reputation: 9

That's almost correct. Just replace the % operator with / operator: cc_num /= 10; That should work :)

Upvotes: 1

Related Questions