PAT A1031 Hello World for U

PAT A1031 Hello World for U


A1031 Hello World for U

题目

如何求得n1、n2值
根据2*n1 + n2 = N + 2,对( N + 2 )/3 进行讨论:

  • ( N + 2 )/3 = 0 ,n1 = n2 = ( N + 2 )/3
  • ( N + 2 )/3 = 1,保证 n2 >= n1,多余的1分给n2
  • ( N + 2 )/3 = 2,保证 n2 >= n1,多余的2分给n2

综上n1 = ( N + 2 ) / 3,n2 = ( N + 2 ) / 3 + ( N + 2 ) % 3

    n1 = (length + 2) / 3;
    n2 = (length + 2) / 3 + (length + 2) % 3;


参考代码
#include 
#include 

int main() {
    char s[10005];
    scanf("%s", s);
    int length = strlen(s);
    int n1, n2, spacecounts;
    n1 = (length + 2) / 3;
    n2 = (length + 2) / 3 + (length + 2) % 3;
    spacecounts = n2 - 2;
    for (int i = 0; i < n1 - 1; ++i) {
        printf("%c", s[i]);
        for (int j = 0; j < spacecounts; ++j) {
            printf(" ");
        }
        printf("%c\n", s[length - 1 - i]);
    }
    for (int i = 0; i < n2; ++i) {
        printf("%c", s[n1 - 1 + i]);
    }
    return 0;
}

你可能感兴趣的:(PAT A1031 Hello World for U)