How to resolve the algorithm Numbers with equal rises and falls step by step in the Swift programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Numbers with equal rises and falls step by step in the Swift programming language

Table of Contents

Problem Statement

When a number is written in base 10,   adjacent digits may "rise" or "fall" as the number is read   (usually from left to right).

Given the decimal digits of the number are written as a series   d:

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Numbers with equal rises and falls step by step in the Swift programming language

Source code in the swift programming language

import Foundation

func equalRisesAndFalls(_ n: Int) -> Bool {
    var total = 0
    var previousDigit = -1
    var m = n
    while m > 0 {
        let digit = m % 10
        m /= 10
        if previousDigit > digit {
            total += 1
        } else if previousDigit >= 0 && previousDigit < digit {
            total -= 1
        }
        previousDigit = digit
    }
    return total == 0
}

var count = 0
var n = 0
let limit1 = 200
let limit2 = 10000000
print("The first \(limit1) numbers in the sequence are:")
while count < limit2 {
    n += 1
    if equalRisesAndFalls(n) {
        count += 1
        if count <= limit1 {
            print(String(format: "%3d", n), terminator: count % 20 == 0 ? "\n" : " ")
        }
    }
}
print("\nThe \(limit2)th number in the sequence is \(n).")


  

You may also check:How to resolve the algorithm Sokoban step by step in the OCaml programming language
You may also check:How to resolve the algorithm Rename a file step by step in the Erlang programming language
You may also check:How to resolve the algorithm Tokenize a string step by step in the 360 Assembly programming language
You may also check:How to resolve the algorithm String prepend step by step in the EchoLisp programming language
You may also check:How to resolve the algorithm Copy a string step by step in the COBOL programming language