You are given a number $N. Write a script to figure out if the given number is Palindrome. Print 1 if true otherwise 0.
#!/usr/bin/tclsh
#
# Palindome Number:
# You are given a number $N. Write a script to figure out if
# the given number is Palindrome. Print 1 if true otherwise 0.
#
if {$argc >= 1} {
set number [lindex $argv 0]
} elseif {$argc == 0} {
puts "Please input a number"
exit
}
if {$number < 0} {
puts "0"
} elseif {$number > 0} {
set p $number
set res 0
while {$p > 0} {
set res [expr $res * 10 + $p % 10]
set p [expr $p / 10]
}
if {$number == $res} {
puts "1"
} else {
puts "0"
}
} else {
puts "1"
}
也可以使用 string reverse 來解。
#!/usr/bin/tclsh
#
# Palindome Number:
# You are given a number $N. Write a script to figure out if
# the given number is Palindrome. Print 1 if true otherwise 0.
#
if {$argc >= 1} {
set number [lindex $argv 0]
} elseif {$argc == 0} {
puts "Please input a number"
exit
}
if {$number < 0} {
puts "0"
} elseif {$number > 0} {
set res [string reverse $number]
if {[string compare $number $res]==0} {
puts "1"
} else {
puts "0"
}
} else {
puts "1"
}
沒有留言:
張貼留言