Wednesday, December 31, 2014

WritingWords

Problem:

TopCoder Problem Statement - WritingWords
Single Round Match 618 Round 1 - Division II, Level One

Overview:

Count how many key presses are needed to type out a word on a cell phone.

Java Source:
01: public class WritingWords {
02: 
03:     public int write(String word) {
04: 
05:         int count = 0;
06: 
07:         for (int i = 0; i < word.length(); i++) {
08:             count += word.charAt(i) - 'A' + 1;
09:         }
10: 
11:         return count;
12:     }
13: }
Notes:

This is about as easy as it gets. It took longer to read the problem description than to actually code it up. Nevertheless, there's still a few things worth noting.

Remember that we can use String.charAt(i) to get the character at a given position in the String. Also chars in java are treated as 16-bit integers, so we can do normal integer arithmetic on them. The letters 'a' - 'z' are guaranteed to be consecutive, as are 'A' - 'Z'. So an expression like 'c' - 'a' will yield a value of 2. In this problem, the actual ascii values of the characters does not matter (A = 65 by the way).

To get the number of key presses for each letter we just subtract 'A' from that letter. But since, 'A' - 'A' would be 0, we need to add 1 to each value.

The variable count is initialized to 0, and then is incremented by the value of each new letter. The operator += is just a sort cut for writing "count = count + ..."

No comments:

Post a Comment