2

I have the following snippet of code:

public static int digPow(int n, int p) {
  int powCounter = p;
  int sum = 0;
  char[] digits = (""+n).toCharArray();

  for (char digit : digits) {
    sum += Math.pow(Character.getNumericValue(digit), powCounter);
    powCounter++;
  }

  if (sum % n == 0) return sum / n;
  else return -1;
}

I don't understand how to define the time complexity, because, even though I have a loop, it seems to me that it's not just O(n). Or it is?

2
  • it seems to me that it's not just O(n) why do you think so? Commented Dec 3, 2022 at 15:02
  • 2
    It's O(log n), assuming Math.pow runs in O(1) time. I'd look carefully at your accuracy though -- you return a long (suggesting the result might not fit in an int), but sum is an int, and Math.pow takes doubles (which represent all int values exactly, but not all long values). Commented Dec 3, 2022 at 15:31

1 Answer 1

1

Its O(n), where n is the length of the character array digits. Since the loop will iterate that no of times the next line is a if else clause which will execute only once.

Sign up to request clarification or add additional context in comments.

1 Comment

Ambiguous though, since a variable n is already present in the code with a different value.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.