Tidy Numbers - Display all positive integers in ascending order
Ananya likes to keep things tidy. Her toys are sorted from smallest to largest and pencils are sorted from shortest to longest. One day, when practicing her counting skills, she noticed that some integers, have their digits sorted in non-decreasing order. She calls 8, 123, 555, and 224488 as numbers tidy. Numbers that do not have this property, like 20, 321, 495 and 999990, are not tidy.
She just finished counting all positive integers in ascending order from 1 to N. What was the last tidy number she counted?
Input
The first line of the input gives the number of test cases, T. T lines follow. Each line describes a test case with a single integer N, the last number counted by Ananya.
Output
For each test case, output is the last tidy number counted by Ananya.
1 ≤ T ≤ 100.
Sample Input:
5
132
1000
7
621
489
132
1000
7
621
489
Sample Output:
129
999
7
599
489
999
7
599
489
Solutions :
<?php $path="input.txt"; //File containing Input elements $fh=fopen($path,"r"); function tidynum($fh) { $res=''; fscanf($fh,"%d",$case); //$case gives no. of test cases for($j=0;$j<$case;$j++) { //Loop moves for total number of cases $no=fgets($fh); //Read each remaining element one by one $arr=str_split(trim($no)); //split number in array. $cnt=count($arr); //Total number of elements in array if($cnt>1) { //If count is greater than one for($i=1;$i<$cnt;$i++) { //Loop until finishes the number $prev=$i-1; //Previous key if($arr[$prev]>$arr[$i]) { //Compare current key to previous key $no=$no-1; //If previous key is greater than current. Substract given number by one $arr=str_split($no); //Again split the remaining number, and do same until number donot set in ascending order $cnt=count($arr); $i=0; } } } $res .=$no; $res .=PHP_EOL; //Used as end of line } return $res; } $res = tidynum($fh); echo $res; ?>
Content in input.txt
5
132
1000
7
621
489
132
1000
7
621
489
Find more algorithm solution in PHP at http://www.fbchandra.com