The Implementation of Rotating Numbers

We call a number X a good number, and if each of its Numbers is rotated 180 degrees one by one, we can still get a valid number that is different from X. Each number is required to be rotated.

A number is valid if each of its digits remains a number after being rotated.0, 1, and 8 are still themselves when rotated;2 and 5 can be rotated into each other (in this case, they rotate in different directions; in other words, 2 and 5 are mirror images of each other); the same thing with 6 and 9, any number other than these is no longer a valid number after rotation.

Now we have a positive integer N, how many numbers from 1 to N is X a good number?

Example:
Input: 10
Output: 4
Explanation:
There are four good Numbers in [1, 10] : 2, 5, 6, 9.
Notice that 1 and 10 are not good Numbers, because they don’t change after rotation.

Subject Analysis
This problem can be solved recursively. When solving this problem, the operation of finding the remainder is used to judge whether the units digit meets the condition of good number.And then we use division to figure out whether the tens place, the hundreds place, or the thousands place is a good number.
After n%10, the program determines whether the remainder matches the good number and is valid. Returns false if n%10 is invalid and not a good number.
If the units digit is valid or good, then the tens digit is judged, then the thousands digit is judged, and so on, up to the highest digit.The Boolean function used for marking is assigned to True if the valid conditions are met from the ones place to the highest place, and one of them is a good number.

Code

package main

import (
	"fmt"
)

func main() {
	var N int
	var answer int
	fmt.Scan(&N)
	answer=rotatedDigits(N)
	fmt.Println("Input:",N," Output:",answer)
	}
func good(n int ,flag bool) bool {
	if n == 0 {
		return  flag
	}
	d := n % 10
	switch d {
	case 3,4,7:
		return  false
		// 3,4,7不为好数且无效
	case 0,1,8:
		return good(n/10,flag) //0,1,8有效但不为好数
	}
	//2,5,6,9 为好数
	return  good(n/10,true)
}

func rotatedDigits(N int) int {
	flag := false
	answer := 0
	for i := 1 ; i <= N; i++{
		if good(i,flag){
			answer++
		}
	}
	return answer
}

Result
在这里插入图片描述

发布了4 篇原创文章 · 获赞 1 · 访问量 91

猜你喜欢

转载自blog.csdn.net/qq_43337384/article/details/105633148