Capitalize 2nd, 4th, 8th, 16th letters in a string


  • 0
    S

    String text = "letters in a string";

    int index = 2;

    StringBuilder sb = new StringBuilder(text);

    while (index < sb.length()) {

    sb.setCharAt(index - 1, Character.toUpperCase(sb.charAt(index - 1)));
    
    index *= 2;
    System.out.println(index);
    

    }

    System.out.println(sb.toString());


  • 0
    H

    Here is my runnable code.

    public class Capitalize{
        public String capitalize(String str){
    
            int index = 2;
            char[] input = str.toCharArray();
    
            while(index <= str.length()){
                input[index - 1] = Character.toUpperCase(str.charAt(index - 1));
                index *= 2 ;
            }
            return String.valueOf(input);
        }
    }
    

  • 0
    U

    Shouldn't the while loop have strictly less than check?

    Additionally why not use the following line instead (char array lookup instead of charAt?
    input[index] = Character.toUpperCase(input[index]);


  • 0
    H

    Thanks for the comments!

    For the first one, I made mistakes about the index of the array as it is zero-based and I corrected the code. (i.e. the 2nd letter of the string is in index 1,...)

    For the second comment, you are absolutely right and I think when I was writing this code, that idea didn't occur to me however, there is no much of difference between them performance-wise.


  • -1
    S
    public static String capitalizeEven(String s) {
        char[] cs = s.toCharArray();
        for (int i = 2; i < cs.length; i *= 2) {
            cs[i-1] = Character.toUpperCase(cs[i-1])
        }
        return new String(cs);
    }

  • 0
    I

    Was this phone or onsite interview?


  • 0
    H

    should we ignore the whitespace?

    assume the string is "letters are".

    without ignore whitespace.(it means we did not count space as a letter) "lEtTrS AeR""
    Ingore whitespace "lEtTrS aEr"


  • 0
    T

    @socram i += 2 is not correct


  • 0
    S

    @tonytata thank you for point it out!

    it should be i *= 2 ... and then i - 1 in the index

    I've also realized that this version above actually capitalize every character whose position is a power of 2; if we want to capitalize ONLY letters, here's an alternative:

    public static String capitalizePowerOfTwoLetters(String s) {
        char[] cs = s.toCharArray();
        int n = 1;
        double l = 0;
        for (int i = 0; i < cs.length; i++) {
            if (Character.isLetter(cs[i])) {
                l++;
                if (l == Math.pow(2, n)) {
                    cs[i] = Character.toUpperCase(cs[i]);
                    n++;
                }
            }
        }
        return new String(cs);
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.