Thursday, 15 September 2011

java - Newbie in Programming - more effecient sumOfDigits -



java - Newbie in Programming - more effecient sumOfDigits -

i came out java code solve sumofdigits.

public static int sumofdigits(int num){ if (num == 0){ homecoming 0; } homecoming num%10+ sumofdigits(num/10); }

well know works, i'm hoping share insights or materials(some formal terms/knowledge) on how improve code efficiency, know java not back upwards recursion well.

recursion not bad tool @ in java. sure, theoretically every function phone call has cost, jit compiler able optimize @ runtime , offer performance. should not optimize function written recursion more cumbersome without it, except if experience problems, uncertainty you'll have code. experience you'll see code legibility matters lot.

to reply question, other way implement want loop until num equals 0 , storing result of partition per 10 in num every time:

int total = 0; while (num != 0) { total += num % 10; num = num / 10; }

java performance

No comments:

Post a Comment