Week5

1. 将字符串反转后返回新字符串

input: "APCS"

return: "SCPA"

public String reverseStr(String str) {
   String result = "";
   for(int i=0; i<str.length(); i++) {
       result = str.substring(i,i+1) + result;
   }
   return result;
}

2. 统计字符串中的空格数

input: "APCS ROCKS THE WORLD"
return: 3

public int countSpaces(String str) {
    int count = 0;
    while(str.indexOf(" ") != -1) {
        count++;
        str = str.substring(str.indexOf(" ")+1);
    }
    return count;
}

3. 返回正整数的因数个数

input: 15
return: 413515

public int countFactors(int num) {
    int count = 0;
    for(int i=1; i<=num; i++) {
        if(num%i==0) {
            count++;
        }
    }
    return count;
}

4. 返回正整数的各位数码之和

input: 15
return: 6(1+5)


public int sumDigits(int num) {
    int digit=0;
    int sum = 0;
    while(num > 0) {
        digit = num % 10;
        sum += digit;
        num /= 10;
    }
    return sum;
}

Last updated