2023华为OD机试真题-箱子之形摆放(JAVA、Python、C++)

题目描述:
有一批箱子(形式为字符串,设为str),要求将这批箱子按从上到下以之形的顺序摆放在宽度为n的空地,请输出箱子的摆放结果。
例如:箱子为ABCDEFG,空地宽度为3,摆放结果如图:

则输出结果为:
AFG
BE
CD
输入描述:
输入一行字符串,通过空格分割,前面部分为字母或数字组成的字符串str,表示箱子;后面部分为一个数字n,表示空地的宽度。例如:
ABCDEFG 3
输出描述:
箱子摆放结果,如题目示例所示
AFG
BE
CD
补充说明:
1. 请不要在最后一行输出额外的空行
2. str只包含字母和数字,1 <= len(str) <= 1000
3. 1 <= n <= 1000
 收起
示例1
输入:
ABCDEFG 3
输出:
AFG
BE
CD
————————————————

import java.util.*;
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNext()) {// 注意,如果输入是多个测试用例,请通过while循环处理多个测试用例
            String str = in.next();
            int width = in.nextInt();
            for (int i = 0; i < width; i++) {
                int k = i;
                int flag = 0;
                while (k<str.length()){
                    System.out.print(str.charAt(k));
                    if (flag == 0){
                        k = 2*width - 1 - 2*i +k;
                        flag = 1;
                    }else{
                        k =k +1+2*i;
                        flag = 0;
                    }
                }
                System.out.println("");
            }
        }
    }
}
import math
text, w = input().split()
w = int(w)
 
cols = ['']* math.ceil(len(text) / w)
 
for i in range(len(text)):
    num_c = i // w
    if num_c % 2 == 0:
        cols[num_c] += text[i]
    else:
        cols[num_c] = text[i] + cols[num_c]
 
#handle the case, the last line is backward and is not full.
if len(cols) % 2 == 0 and len(cols[-1]) != w:
    cols[-1] = (w- len(cols[-1])) * ' ' + cols[-1]
 
result = [''] * w
 
for i in range(w):
    for col in cols:
        if i < len(col) and col[i] != ' ':
            result[i] += col[i]
for res in result:
    if res == '':
        continue
    print(res)
#include<iostream>
#include<vector>
using namespace std;
int main(){
    string s;
    cin>>s;//字符串
    int n;
    cin>>n;//宽度
    vector<string> vec(n);
    for(int i=0;i<s.size();i++){
        int j=i%n;
        if(i/n%2==1){//奇数
            j=n-1-i%n;
        }
        vec[j]+=s[i];
    }
    for(int i=0;i<n;i++){
            cout<<vec[i]<<endl;
    }
    system("pause");
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值