[QWERT] Locate non-zero numbers start and end from a string of numbers
2012-10-23 10:22
441 查看
Input is a string of numbers:
0012300123400012012311
Output will list the none-zero numbers' start and length.
Perl语言: 高亮代码由发芽网提供
my $nums = shift;
my $output = &cluster($nums);
print $output . "\n";
sub cluster{
my $nums = $_[0];
my @nums = (split //,$nums);
my $indicator = 0;
my $len = 0;
my $start= 0;
my $lens = '';
my $starts= '';
foreach my $n (0..@nums-1){
if ($nums[$n]>0){
$len++;
if ($indicator==0 || $num = @nums -1){
$start = $n;
$indicator =1;
}
}
elsif ( $nums[$n]<=0 ) {
if ( $indicator==1) {
$starts = $starts . $start . ",";
$lens = $lens . $len . ",";
$len = 0;
$indicator =0;
}
}
}
return ($starts . "\t" . $lens );
}
0012300123400012012311
Output will list the none-zero numbers' start and length.
Perl语言: 高亮代码由发芽网提供
my $nums = shift;
my $output = &cluster($nums);
print $output . "\n";
sub cluster{
my $nums = $_[0];
my @nums = (split //,$nums);
my $indicator = 0;
my $len = 0;
my $start= 0;
my $lens = '';
my $starts= '';
foreach my $n (0..@nums-1){
if ($nums[$n]>0){
$len++;
if ($indicator==0 || $num = @nums -1){
$start = $n;
$indicator =1;
}
}
elsif ( $nums[$n]<=0 ) {
if ( $indicator==1) {
$starts = $starts . $start . ",";
$lens = $lens . $len . ",";
$len = 0;
$indicator =0;
}
}
}
return ($starts . "\t" . $lens );
}
相关文章推荐
- 正则表达式学习指南(七)----Start of String and End of String Anchors
- PHP: Get start and end dates of a week from date(‘W’) [转]
- Leetcode_remove-nth-node-from-end-of-list(c++ and python version)
- Select n numbers from 1 to m with all of array 'all' and none of array 'none'
- [Regular Expressions] Find the Start and End of Whole Words
- [Javascript] String Padding in Javascript using padStart and padEnd functions
- A context path must either be an empty string or start with a '/' and do not end with a '/' 问题解决方法
- GetStartAndEndString
- [Regular Expressions] Match the Start and End of a Line
- Swap kth element from the beginning and kth element from the end of linked list -- Amazon
- Remove Nth Node From End of List
- LeetCode-Remove Nth Node From End of List
- Bitwise AND of Numbers Range
- Codeforces Round #432 (Div. 1) B. Arpa and a list of numbers
- Get json formatted string from web by sending HttpWebRequest and then deserialize it to get needed data
- Bitwise AND of Numbers Range
- [Leetcode] Bitwise And of numbers range
- Remove Nth Node From End of List
- LeetCode 201 Bitwise AND of Numbers Range
- Remove Nth Node From End of List