I have the following pseudo-code:
read n
p <- 1;
m <- 0;
k <- 0;
while ( n != 0 )
read x
for ( i <- 1, k )
x <- [x / 10]
if ( x != 0 )
c <- x % 10
else
c <- n % 10
m <- c * p + m
n <- [n / 10]
p <- p * 10
k <- k + 1
write m
and I have to transform this code such that we have just 1 loop. I went over examples over and over again and I don't see what I should do. I think we need that first while
loop so I kept trying to get rid of that for
loop function but I don't see how I could get the same behavior with just one loop.
(Excuse the terrible style of pseudo-code)
If you are talking about the
for ( i <- 1, k )
x <- [x / 10]
loop, it divides x
by 10 ** k
, and
x <- [x / 10**k]
accomplishes exactly what the loop does. If you have a feeling that raising to a power is a loop in disguise, consider
power_of_ten = 1
while ( n != 0 )
read x
x <- [x / power_of_ten]
....
power_of_ten <- power_of_ten * 10