shell實現FizzBuzzWhizz問題樣本(拉勾網面試題)_linux shell

來源:互聯網
上載者:User

試題: https://www.jinshuju.net/f/EGQL3D

語言: Shell (Bash)
運行方式:
sh num-game.sh 數字1 數字2 數字3
如果不想使用傳遞數位方式, 可以修改 num-game.sh 第 9 行, 將
NUM=$*
改為
NUM='數字1 數字2 數字3'
然後直接運行 sh num-game.sh 即可

複製代碼 代碼如下:

#!/bin/bash

## Author : TaxKiz
## Email  : taxkiz@gmail.com

export PATH='/bin:/sbin:/usr/bin:/usr/sbin'

## NUM='3 5 7'
NUM=$*

## 檢查輸入的數字個數是否為 3 個
function CT () {
    [ $( echo $* | sed 's/ /\n/g' | wc -l ) != '3' ] && echo " Please Enter 3 Number ! " && exit 1
}

CT $NUM

## 個位元列表
NT='1/2/3/4/5/6/7/8/9'

## 檢查輸入的數字是否為個位元
function CK () {
    for num in $*
    do
        [ $num == '0' ] && echo "Error Number '$num'" && exit 2
        echo $NT | grep "\b$num\b" > /dev/null 2>&1
        [ $? != '0' ] && echo "$num is not a single digit" && exit 3
    done
}

CK $NUM

## 判斷是否有重複的數字
function SN () {
    if [ $1 == $2 ] || [ $1 == $3 ] || [ $2 == $3 ]; then
        echo "ERROR! There have same number : '$*'"
        exit 4
    fi
}

SN $NUM

## 大喊一聲
function GO () {

    A1=$1
    A2=$2
    A3=$3

    T1=$(( $1 * $2 ))
    T2=$(( $1 * $3 ))
    T3=$(( $2 * $3 ))

    TA=$(( $1 * $2 * $3 ))

    for num in {1..100}
    do
        echo $num | grep $A1 > /dev/null 2>&1
        [ $? == '0' ] && echo 'Fizz' && continue

        echo "scale=2; $num/$TA" | bc | grep 00 > /dev/null 2>&1
        [ $? == '0' ] && echo 'FizzBuzzWhizz' && continue

        echo "scale=2; $num/$T1" | bc | grep 00 > /dev/null 2>&1
        [ $? == '0' ] && echo 'FizzBuzz' && continue

        echo "scale=2; $num/$T2" | bc | grep 00 > /dev/null 2>&1
        [ $? == '0' ] && echo 'BuzzWhizz' && continue

        echo "scale=2; $num/$T3" | bc | grep 00 > /dev/null 2>&1
        [ $? == '0' ] && echo 'FizzWhizz' && continue

        echo "scale=2; $num/$A1" | bc | grep 00 > /dev/null 2>&1
        [ $? == '0' ] && echo 'Fizz' && continue

        echo "scale=2; $num/$A2" | bc | grep 00 > /dev/null 2>&1
        [ $? == '0' ] && echo 'Buzz' && continue

        echo "scale=2; $num/$A3" | bc | grep 00 > /dev/null 2>&1
        [ $? == '0' ] && echo 'Whizz' && continue

        echo $num

    done
}

GO $NUM

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.